Dependent Dropdowns (Linked Selects) with single class (no other selectors)

Posted by AJ on Stack Overflow See other posts from Stack Overflow or by AJ
Published on 2010-05-20T01:58:16Z Indexed on 2010/05/20 2:10 UTC
Read the original article Hit count: 236

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about html-select