简体   繁体   中英

Set combobox selected item from JavaScript

I have JavaScript function which besides other stuff generates combobox option values. This combobox is by default hidden and it has empty option values. On certain page event this combobox is shown to the user with generated option values (0 to 5). Inside same function which generates those values I want to set combobox option value to be selected first from generated list, index 0.

So I tried the following but nothing changes. Combobox has no selected item:

var myComboBox = $("#myCombo");
 for (i = 4; i < checked; i++) {
     myComboBox.append('<option value=' + i + '>' + i + '</option>');
 }
 myComboBox.selectedIndex = 0;

myComboBox is a jQuery object, not a DOM element... therefore:

myComboBox[0].selectedIndex = 0;

OR

myComboBox.prop('selectedIndex', 0);

If you want to select the option by value instead you can also do:

myComboBox.val(someValue);

I would say that it's a good practice to put $ in front of variables that references jQuery objects to avoid any confusion, such as $myComboBox . This naming convention is pretty common.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM