admin管理员组

文章数量:1426782

I need your help.

I am a newbie to javascript and I am unsure as to how I would go about searching for a specified option in a select box and then selecting it

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>

ie.

lookup("select1","mangos")

javascript logic:

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

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

if found { select mangos from the select box }

}

How do you code that ?

Thanks in advance,

I need your help.

I am a newbie to javascript and I am unsure as to how I would go about searching for a specified option in a select box and then selecting it

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>

ie.

lookup("select1","mangos")

javascript logic:

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

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

if found { select mangos from the select box }

}

How do you code that ?

Thanks in advance,

Share Improve this question edited Feb 9, 2015 at 7:03 Razan Paul 13.9k3 gold badges73 silver badges61 bronze badges asked Jul 27, 2013 at 20:50 John SmithJohn Smith 1,68711 gold badges38 silver badges52 bronze badges 1
  • Are you trying to get the element itself or what exactly – John Commented Jul 27, 2013 at 20:51
Add a ment  | 

3 Answers 3

Reset to default 1

This is easier than you think... try:

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;
}

Via Jquery:

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

本文标签: javascriptSearching and selecting an option value in a HTML select elementStack Overflow