选择< select>项目的价值 [英] select <select> item by value

查看:80
本文介绍了选择< select>项目的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

 < select id =x> 
< option value =5> hi< / option>
< option value =7> hi 2< / option>
< / select>

我需要一个javascript函数,使我可以选择并显示<选项> 作为id的默认值。换句话说,我想要一个 setOption(5)< option> 值为5 作为默认值显示在组合框中。



这可能吗?

解决方案如果可以的话,用ES6 ...

pre $函数setOption(selectElement,value){
返回[... selectElement.options] .some((option,index)=> {
if(option.value == value){
selectElement.selectedIndex = index;
return真;
}
});
}

...否则...

 函数setOption(selectElement,value){
var options = selectElement.options;
for(var i = 0,optionsLength = options.length; i< optionsLength; i ++){
if(options [i] .value == value){
selectElement.selectedIndex =一世;
返回true;
}
}
返回false;
}

setOption(document.getElementById('my-select'),'b');

false ,那么值不可能是发现:)

i have

<select id="x">
    <option value="5">hi</option>
    <option value="7">hi 2</option>
</select>

I want a javascript function that enables me to select and display the <option> as default one by id. In other words, I want to do a setOption(5) and the <option> with the value "5" to be displayed in the combobox as a default .

Is that possible?

解决方案

If you can, with ES6...

function setOption(selectElement, value) {
    return [...selectElement.options].some((option, index) => {
        if (option.value == value) {
            selectElement.selectedIndex = index;
            return true;
        }
    });
}

...otherwise...

function setOption(selectElement, value) {
    var options = selectElement.options;
    for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
        if (options[i].value == value) {
            selectElement.selectedIndex = i;
            return true;
        }
    }
    return false;
}

setOption(document.getElementById('my-select'), 'b');

See it!

If it returns false, then the value could not be found :)

这篇关于选择&lt; select&gt;项目的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆