I have a select in a form with a button next to it. Below is an unknown quantity of other select fields.
<select class="offer_1 value_source" name="xnamex">
<option value="">Please Select</option>
<option value="xxxxxxx">Text</option>
</select>
<button class="copy_select offer_1" type="button" name="Copy" value="">Copy Down</button>
<select class="offer_1" name="xnamex">
<option value="">Please Select</option>
<option value="xxxxxxx">Text</option>
</select>
<!-- unknown quantity of selects follow -->
I am grouping the select fields and button together via the class offer_{number}
I want to copy the selected value from the one select with the class value_source to all other selects with the same class (offer_{number}).
Here is my current code:
$(document).ready(function() {
$('.copy_select').click(function() {
attr_class = $(this).attr('class');
attr_class = attr_class.replace('copy_select ', '.');
$(attr_class).val($(attr_class + ' value_source').val());
alert(attr_class);
});
});
All selects remain unselected and my copy_source get reset to unselected.
What am I doing wrong?
Also, how would I check that the select has a value set and throw up an alert() if not?
Many, many thanks for your time 🙂
Not sure what’s wrong with your original example, this does what I think you want to do. That is, when the button is clicked, select the current value from
select.offer_1.value_sourcein all other selects with the classoffer_1; and not to selects with the classoffer_2which will be handled with another button.JavaScript
HTML
(I’m using a data attribute on the
<button>to associate the button with the<select>s because data attributes are awesome and parsing CSS class strings isn’t.)Obligatory jsFiddle example.