I have two selection fields;
<label>Color:</label>
<select id="color">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
<label>Car:</label>
<select id="car"></select>
I would like to implement the feature that if color “red” is selected, update the car selection options to be “red car 1” and “red car 2”. If color “Blue” is selected, update the car options to be “blue car 1” and “blue car 2”.
I implement this feature in the following way:
var updateOptions = function(carField, options) {
carField.empty();
for (var i = 0; i < options.length; i++) {
carField.append("<option value=" + options[i] + ">" + options[i] + "</option>");
}
};
var colorField = $('#color');
var carField = $('#car');
colorField.change(function() {
if (colorField.val() === 'red') updateOptions(carField, ['red car 1', 'red car 2']);
else if (colorField.val() === 'blue') updateOptions(carField, ['blue car 1', 'blue car 2']);
});
Things are fine here. The only problem is, the car selection options get updated only if user select the color. The page first load will not update the car selection options. For example, “red” color is the default selected color when page loaded, but the car field is empty after page get loaded. How to get rid of this efficiently?
Try adding this code: (outside any function)