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 ?
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With