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 SELECT
s; 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 SELECT
s 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
UPDATE:
Here is somewhat better description:
- There are more than 2 `SELECT`s on the page with class `someclass`. SELECT[0] has some values initially and its successors are empty as they will change based on the value of their respective immediate ancestor.
- If there is a change in `SELECT[i]`, it fires an event and `SELECT[i+1]` is populated with appropriate `OPTION`s.
- `SELECT[i+2]` and further successors are reset if they had any data before. So, only immediate child is populated but further successors are reset.
I hope I articulated well. Please let me know if you need more clarification on what I want.