2013-07-27 49 views
1

我需要你的幫助。搜索並選擇HTML選擇元素中的選項值

我是一個新手,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 } 

} 

你怎麼代碼?

由於提前,

+0

你試圖讓該元素本身或者究竟是什麼 – John

回答

1

這是比你想象的更容易...嘗試:

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

通過jQuery:

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