Dependent Dropdowns (Linked Selects) with single class (no other selectors)
- by AJ
I am trying to create multiple dependent dropdowns (selects) with a unique way. I want to restrict the use of selectors and want to achieve this by using a single class selectors on all SELECTs; by figuring out the SELECT that was changed by its index. Hence, the SELECT[i] that changed will change the SELECT[i+1] only (and not the previous ones like SELECT[i-1]).
For html like this:
<select class="someclass">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class="someclass">
</select>
<select class="someclass">
</select>
where the SELECTs other than the first one will get something via AJAX.
I see that the following Javascript gives me correct value of the correct SELECT and the value of i also corresponds to the correct SELECT.
$(function() {
$(".someclass").each(function(i) {
$(this).change(function(x) {
alert($(this).val() + i);
});
});
});
Please note that I really want the minimum selector approach. I just cannot wrap my head around on how to approach this. Should I use Arrays? Like store all the SELECTS in an Array first and then select those?
I believe that since the above code already passes the index i, there should be a way without Arrays also.
Thanks a bunch.
AJ