I have a form that has many select inputs that are grouped by theme. I have a master select for each group that allows a user to set all selects in a group to the master value (gradescales is a method that provides grades 1-8).
How could I go about DRYing this up?
FORM
<label>Change all to:</label>
<%= select_tag "section_one", options_for_select(gradescales), :id => "section_one_master" %>
<div id="section_one_wrapper">
<%= f.input :item_one, :collection => gradescales %>
<%= f.input :item_two, :collection => gradescales %>
<%= f.input :item_three, :collection => gradescales %>
<%= f.input :item_four, :collection => gradescales %>
</div>
jquery functions look like:
$("#section_one_master").change( function() {
var a = $("#section_one_master").val();
$("#section_one_wrapper select").val(a);
});
$("#section_two_master").change( function() {
var a = $("#section_two_master").val();
$("#section_two_wrapper select").val(a);
});
...again, and again
So, when section_one_master is changed, the function is hit and all the select inputs inside the section_one_wrapper div are changed to match whatever value was chosen in the master.
I have many groups, each with a master select input. How could I DRY this up to one function, and then dynamically id the master that called the function in the first place and use convention to change the appropriate grouped selected?
You can add classes to your master section elements:
Note that in the context of change handler
thisrefers to the element, you don’t have to reselect the element.You can also select the section wrapper elements and cache the object and use
filtermethod, by caching the object, you only select those elements once, which is better than re-selecting them.