开发者

Page first load, options did not update, how to solve?

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开发者_Go百科 get loaded. How to get rid of this efficiently?


Try adding this code: (outside any function)

$(document).ready(function() {
  $('#color').change();
});


While loading page make a call like this -

updateOptions(carField, ['red car 1','red car 2']);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜