简体   繁体   中英

dynamically select value from drop down list

I have the following drop down list:

<select name="selSS1" id="select_value">
    <option value="val0">sea zero</option>
    <option value="val1">sea one</option>
    <option value="val2">sea two</option>
    <option value="val3">sea three</option>
    <option value="val4">sea four</option>
</select>

I would like to dynamically select a value from that list using javascript:

I tried:

document.getElementById('select_value').selected ="val3";

But the above code does not seem to work. Any help is most appreciated.

Use the following line:

 document.getElementById('select_value').value ="val3";

or 

    document.getElementById('select_value').selectedIndex = 3;

Hope this solves ur problem.

$('#select_value').val('val0');

With plain JavaScript:

var element = document.getElementById("select_value");
var selectedValue = element.options[element.selectedIndex].value;

try:

var mySelect = document.getElementById('select_value');
mySelect.getElementsByTagName('option')[index].setAttribute('selected','selected');

where index stands for the position of the option you want to select.

尝试这种方式:

document.getElementById('select_value').option[3].selected;

这将选择值3

document.getElementById('select_value').selectedIndex=3;

If you want to set the selected one by the value, try this function. By declaring a function you will be able to use this functionality with any select :).

// Simplest version

function setSelected(select_id,value){

    document.getElementById(select_id).value = value;

}

// Or, complex version

function setSelected(select_id,value){

    var mySelect = document.getElementById(select_id);
    var options = mySelect.options;
    var key;
    for(key in options){

        if(options[key].value===value){
            options[key].setAttribute("selected","");
        }
        else
            options[key].removeAttribute("selected");
    }
}

in your case:

setSelected("select_value","val3");

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