I’ve got a load of dropdowns on a html page and I want to fire events when they change (eventually it’ll be updating all of the dropdowns with content through ajax) – but for now i’m just trying to make it alert out the data element i’ve selected. I don’t want it to fire on every drop down on the page, just the ones with the corresponding css class. I.e. group1 group2. The groups will have to be dynamic too as I don’t know how many there could be.
Theres a js fiddle above with how it is at the moment. I expect it to only alert 4 times the when you change one of the first 4 dropdowns and only twice when you do the second. But clearly i’m doing something wrong!
My html is:
<select id="test1" class="group1" data-type="Select Box 1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group1" data-type="Select Box 2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group1" data-type="Select Box 3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group1" data-type="Select Box 4">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group2" data-type="Select Box 5">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group2" data-type="Select Box 6">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
My JS is:
$(document).ready(function() {
$('select').change(function() {
$('.group1').each(function() {
alert($(this).data('type'));
});
$('.group2').each(function() {
alert($(this).data('type'));
});
});
});
You can do it like this
http://jsfiddle.net/wirey00/6BakA/4/
Or even better since you don’t know how many selects there’ll be, delegating the event will be more efficient since the parent element will be listening and handling the event. You can replace
bodywith any parent element of theselectboxes that’s available when the dom is loadedhttp://jsfiddle.net/wirey00/6BakA/5/