开发者

Select dropdown menu option with javascript

I have a dropdown menu and I cannot figure out how to make a javascript function select a drop down menu option. I have tested the output of the variables and they are all correct, but it still will not select the option when clicked. Here is the function and drop down menu.

Function

function formFill(a, b, c){
        theform.from.value = a;
        theform.to.value = b;
        for(var i = 0;i < document.getElementById("stateSelect").length;i++){
            if(document.getElementById("s开发者_开发技巧tateSelect").options[i].value == c ){
                document.getElementById("stateSelect").selected = true;
            }
        }
    }

Menu item

<select id="stateSelect" name="stateSelect">
    <option value="none">(None)</option>
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>


Change the line that reads:

document.getElementById("stateSelect").selected = true;

to:

document.getElementById("stateSelect").selectedIndex = i;


Alt. you can set selected to the actual option: select.options[i].selected = true;

...
        var select = document.getElementById("stateSelect");
        for(var i = 0;i < select.options.length;i++){
            if(select.options[i].value == c ){
                select.options[i].selected = true;
            }
        }
...


I used Anatoly's solution above (thanks!) until a coworker pointed out I could simplify it further with

var select = document.getElementById("stateSelect");
select.options.forEach(opt=>{
    if(opt.value == c)
        opt.selected = true;
    })

which he claims requires less overhead, though I could only speculate why.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜