Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display specific data based on a combo box selection

I have 2 combo boxes. I want to display specific data in combo box 2 based on combobox 1 selection.

But I want to make it an ontime selection ... so when I press on the option I want from combobox 1 , combobox 2 is filled with data matching this selection.

I tried to put an on click function on combobox 1 options, but it didn't work when I click on them ... So is there some method to do so ?

like image 787
Sana Joseph Avatar asked Apr 24 '26 08:04

Sana Joseph


2 Answers

Assign the change event handler on the first dropdown, and then, based on the selected value, fetch the values that ought to be put in the second dropdown. Here's a typical manufacturer -> model example:

Markup:

​<select id="manufacturers">
    <option></option>
    <option value="Audi">Audi</option>
    <option value="Toyota">Toyota</option>
</select>

<select id="cars">
</select>

JavaScript:

​​var cars = {
    Audi: [ 'A2', 'A3', 'A4' ],
    Toyota: [ 'Auris', 'Avalon', 'Yaris' ]
}​​​​;

$("#manufacturers").change(function () {
   var $this = $(this);
   var selectedValue = $this.val();
   if (selectedValue) {
     var $cars = $("#cars").empty();
     var newCars = cars[selectedValue];
     $.each(newCars, function () {
         console.log(this);
       $("<option>" + this + "</option>").appendTo($cars);
     });
   }
});

DEMO.

like image 116
João Silva Avatar answered Apr 26 '26 20:04

João Silva


You should use the change (not click) event on the select tag itself (not on the option tag). Example:

$('#combo1').change(function() {
     // Load new content for #combo2 here
});
like image 25
Leif Avatar answered Apr 26 '26 21:04

Leif