John Smith
John Smith

Reputation: 1687

Searching and selecting an option value in a HTML select element

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,

Upvotes: 1

Views: 8316

Answers (3)

Razan Paul
Razan Paul

Reputation: 13838

Via Jquery:

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

Upvotes: 1

scunliffe
scunliffe

Reputation: 63588

This is easier than you think... try:

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

Upvotes: 1

John
John

Reputation: 6268

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

Upvotes: 1

Related Questions