繁体   English   中英

在HTML select元素中搜索并选择选项值

[英]Searching and selecting an option value in a HTML select element

我需要你的帮助。

我是javascript的新手,我不确定如何在选择框中搜索指定的选项,然后选择它

HTML:

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<select id="select1">
   <option value="apples">apples</option>
   <option value="oranges">oranges</option>
   <option value="bananas">bananas</option>
   <option value="mangos">mangos</option>
   <option value="pears">pears</option>
 </select>

</body>

</html>

即。

lookup("select1","mangos")

javascript逻辑:

function lookup("selectid","stringtosearchfor") {

look through the selected "selectid" and find the string "mangos"

if found { select mangos from the select box }

}

你是如何编码的?

提前致谢,

function lookup(id, value)
{
    var ret = undefined;

    if(document.getElementById(id) != undefined)
    {
        var options = document.getElementById(id).childNodes;

        for(i = 0; i < options.length; i++)
        {
            if(options[i].value == value)
            {
                ret = options[i];
                break;
            }
        }
    }

    return ret;
}

这比你想象的容易...尝试:

document.getElementById('select1').value = 'mangos';

通过Jquery:

$('#select1').val('mangos');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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