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

Searching and selecting an option value in a HTML select element

本文关键字:选择 选项 搜索 HTML 元素      更新时间:2023-09-26

我需要你的帮助。

我是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 }
}

你是怎么编码的?

提前感谢,

这比你想象的要容易。。。尝试:

document.getElementById('select1').value = 'mangos';
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;
}

通过Jquery:

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