Question

My problem is simple. Consider the common car brand - model example as shown below:

<select id="brand">
    <option value="">Choose</option>
    <option value="audi" class="a1 a3 a4">Audi</option>
    <option value="bmw" class="3-series 5-series 7-series">BMW</option>
</select>

<select id="model">
    <option value="">Choose</option>
    <option value="A1" class="audi">A1</option>
    <option value="A3" class="audi">A3</option>
    <option value="A4" class="audi">A4</option>
    <option value="3-series" class="bmw">3-series</option>
    <option value="5-series" class="bmw">5-series</option>
    <option value="7-series" class="bmw">7-series</option>
</select>

I can easily chain the models to the brands using the JQuery Chained plugin, like this:

$("#model").chained("#brand");

But I want it to work the other way around as well. So if the car brand select is empty, I want the full model list. Selecting A1 in the second select would then select Audi in the first dropdown.

I simply added this line:

$("#brand").chained("#model");

But that doesn't work, as it renders both selects readonly (see jsFiddle). Is there a way to achieve what I want?

Was it helpful?

Solution

Not familiar with the chained function but you should be able to do something like this:

$("#brand").change(function(){
  if($("#model").val()==""){
    $("#model").val($("#brand:selected").attr("class"));
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top