Is it possible to access the ID of a collection_select and have a list of items appear whenever the selection is modified?

I am working on a form

named _form.html.erb

<%= simple_form_for(@exam) do |f| %>
  <%= f.error_notification %>

  <div class="field">
    <%= f.label :Year %>
    <%= f.collection_select :year_id, Year.order(:name), :id, :name, prompt: true %>
  </div>


  <div class="form-inputs">
    <%= f.input :marks_secured %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "Submit" %>
  </div>
<% end %>

Whenever the select box changes (i.e. a different year is selected), I want to show the list of students for that specific year on the same page.

I'm unsure about how to retrieve the ID of the selected item and integrate it back into the view/controller to make this happen..

Below are my models:

student.rb

class Student < ApplicationRecord
  belongs_to  :year
  has_many  :exams
end

exam.rb

class Exam < ApplicationRecord
  belongs_to  :year
  belongs_to  :student
end

year.rb

class Year < ApplicationRecord
  has_many  :students
  has_many  :exams
end

Answer №1

To efficiently display the list of students every time the selection option changes, I suggest incorporating ajax into your setup. This will require making a few modifications.

Firstly, pinpoint where in your view you want to showcase the students. For example, consider adding a div within your form:

<%= simple_form_for(@exam) do |f| %>
  <%= f.error_notification %>

  <div class="field">
    <%= f.label :Year %>
    <%= f.collection_select :year_id, Year.order(:name), :id, :name, prompt: true %>
  </div>

  <div id="students"><!-- Students will be listed here --></div>

  <div class="form-inputs">
    <%= f.input :marks_secured %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "Submit" %>
  </div>
<% end %>

Next, include a script (within the same view as your form) to detect when the select changes and dynamically update the students list using ajax:

<script type="text/javascript">
  $(function () {
    function getStudents() {
      var year = $('#exam_year_id').val();

      $.ajax({
        headers: {
          'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        },
        type: "GET",
        url: "<%= students_url %>",
        data: { year: year },
        success: function(response) {
          $('#students').html(html);
        }
      });
    }

    $('#exam_year_id').on('change', getStudents );
    getStudents();
  });
</script>

In this scenario, the function getStudents is invoked whenever the select changes (

$('#exam_year_id').on('change', getStudents );
) and upon page load (getStudents();), listing the default year's selected students upon initial page load.

Note that we are replacing the content of the recently added div with a variable named html, which will be generated within a view by your students controller (next step).

Subsequently, update your students controller to fetch the student list for the chosen year:

def index
  @Students = Student.where(year: params[:year])
end

Create the corresponding view displaying the student list:

var html = "<select name='exam[student_id]' id='exam_student_id'>";

<% @Students.each do |student| %>
  html = html + "<option value='<%= student.id %>'><%= student.name %></option>"
<% end %>

html = html + "</select>";

The view should be named index.js.erb instead of

index.html.erb</code and will contain javascript. In this example, it only comprises the variable <code>html
with the student list (presented as another select box but customizable).

Lastly, add an update action to your exams controller to modify the exam details:

def update
  exam = Exam.find(params[:id])
  exam.student_id = exam_params[:student_id]
  exam.year_id = exam_params[:year_id]
  exam.save!
end

private

def exam_params
  params.require(:exam).permit(:year_id, :student_id)
end

And there you have it! I hope this explanation proves useful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to integrate JQuery URL in Joomla components?

Can anyone show me how to load a jquery URL in Joomla (Component)? I have a button that, when clicked, will reload the page and use the GET method to display a value from a variable. JavaScript: jQuery("#btnclickme").click(function(){ jQuery("#divpro").l ...

Trouble with CSS animation when incorporating JavaScript variables from a PHP array

Whenever I use a script to fetch an array of objects from PHP... I successfully display the results on my website by outputting them into Divs. The challenge arises when I introduce CSS animations. The animation only triggers if the variable length excee ...

Is there a way to retrieve the JSON url from the input box

My goal is to retrieve a JSON file from a URL entered in a text box. I have identified the text box as txtr and used jQuery to get the value like this: var txtbval = $("#txtr").val();. I then included this value in the JSON parsing script as follows: url: ...

Tips on saving php variable content in HTML "id"

Three variables are used in PHP: message_id, message_title, and message_content. Their content is stored inside HTML 'id' for later use with jQuery. Example: Variables: $id_variable = $rows['id_mensagem']; $message_title_edit = $rows ...

unable to display picture on puggy

Check out the code snippet below: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <title>Home Page</title> </head> <body> <img src="resources/mainlogo.png" style="width:304px;height:2 ...

Having trouble importing OrbitControls in three.js with an error?

I'm currently working on localhost and I've encountered an issue while trying to import "orbitcontrols()" which is not functioning properly and displaying an error. Here is the error message main.js:1 Uncaught SyntaxError: Cannot use import stat ...

Enhance your website with a unique hover and left-click style inspired by the functionality of file explorer

I have a set of items like this: I am trying to replicate the functionality of a file explorer in terms of item selection. To clarify, I aim to create a feature where hovering over an item and left-clicking it would generate a virtual rectangle to select ...

Getting started with a project using meteor.js and vue.js

As a beginner in meteor.js, I am eager to create a project using both meteor.js and vue.js. However, I am struggling to find the right method for managing files in meteor.js. Could someone please assist me by providing a demo project or video link that c ...

Error in AngularJS v1.2.5 when using textarea with placeholder attribute in IE11

Having trouble with an Angular JS v1.2.5 form that is not functioning in IE11, despite working perfectly in Firefox, Chrome, and Safari. The issue seems to be related to using interpolation inside the placeholder attribute of a textarea. <body ng-con ...

Best practices for timeout in HTTP long polling

As an avid user of Javascript AJAX and long-polling, I am constantly seeking the best value for server response timeout. Despite scouring numerous documents, a detailed explanation for timeout continues to elude me. Some suggest 20 seconds, while others ...

Set a variable to a specific cell within a table

I've been attempting to insert images into a table and have had success so far - clicking cycles through the available options. However, I've encountered an issue where the counter is not cell-specific but rather global. Is there a way to create ...

What steps can be taken to troubleshoot issues with the jquery mask plugin?

I am using the jQuery Mask Plugin available at to apply masks to input fields on my website. Currently, I am trying to implement a mask that starts with +38 (0XX) XXX-XX-XX. However, I am facing an issue where instead of mandating a zero in some places, ...

Search for text within the nearest <p> tag using HTML and jQuery

My table contains different td elements with the same ID, as shown in this foreach loop: <td class="AMLLeft" style="display:inline-block; !important">ID: <p class="important">${item.id}</p> </td> <td align="right" nowrap="tr ...

AngularJs is not responsive to sending POST requests with hidden <input> values

Within my web application, there are multiple forms on a single page. I am looking to utilize AngularJS to submit a specific form. Each form requires a unique ID with a hidden value for submission. However, using value="UNIQUE_ID" in a hidden input field ...

Encountering an unrecognized error on Windows when attempting to execute a child process with regex return

Below is the code I am utilizing to retrieve Make file targets: const command = `make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\\/t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'`; cp.exec(command, options, (error, stdout, s ...

Mix up table data cells using Javascript/jQuery

Can anyone provide me with some helpful tips? I'm really struggling with this. My Objective I aim to create a table with two columns ("name" and "rating"), consisting of 5 rows. 2 of these rows should have a random "rating" between 6-10 2 other ro ...

Formik button starts off with enabled state at the beginning

My current setup involves using Formik validation to disable a button if the validation schema is not met, specifically for a phone number input where typing alphabets results in the button being disabled. However, I encountered an issue where initially, ...

Creating a Javascript object from a JSON string

Looking for a way to convert a JSON string into a JavaScript object? You can make use of the following code snippet obtained from the server: JSON String: ["{"title":"Admin Dhaka","href":"#0","dataAttrs":[],"data":["{\"title\":\"BNS HAJI M ...

The value entered for creating a payment method is invalid: the card must be in the form of an object

I am in the process of setting up a payment method using the Next.js library from Stripe. Here is the code snippet: import React, { FunctionComponent } from 'react'; import type { DisplaySettingsProps } from '@company/frontoffice/types' ...

I'm encountering a type error stating that children are not defined when attempting to establish parent-child relationships from a flat array. What

Trying to establish a parent-child relationship between modules based on their IDs. Ran into an issue with the function I used, as it returned an error stating that children were not defined. const data = [ { module_id: "96ac027b-b5ce-4326-b5db- ...