2012-12-14 178 views
1

我需要你的幫助創建一個功能,允許我從一個下拉框(使用javascript) 基於給定的變量選擇給定的選項名稱,如果值不存在,然後將其添加到下拉列表中,然後選擇它。從下拉框添加和選擇一個選項值

例子:

<html> 

<head> 

<script type="text/javascript"> 

function test() { 

var option_name_to_look_for = "mangos" 

if option_name_to_look_for is listed in the drop down box (drop) then select it 

if the option_name_to_look_for is not listed in the drop down box (drop), automatically add it to the drop down list (drop) and select it. 

} 

</script> 

</head> 

<body> 

<select id="drop" style="width: 200px;"> 
<option value="0"></option> 
<option value="1">apples</option> 
<option value="2">oranges</option> 
<option value="3">pears</option> 
<option value="4">mangos</option> 
<option value="5">bananas</option> 
<option value="6">kiwis</option> 

</select> 

</body> 

</html> 
+1

你是否有在所有的任何工作的js?如果是的話,我們可以得到一個小提琴? –

回答

1

非jQuerified版本!

function selectMe(name){ 
    var select = document.getElementById("drop"), 
     options = select.options, 
     found = false; 

    //Search for it! 
    for (var x=0; x<options.length; x++){ 
    if(options[x].text==name){ 
     options[x].selected=true; 
     found = true; 
     break; 
    } 
    } 

    //if it isn't found, add it! 
    if(!found){ 
    var option = document.createElement("option"); 
    option.text = name; 
    option.value = options.length; 
    select.appendChild(option); 
    option.selected=true; 
    } 
} 

selectMe("mangos"); 
1

使用jQuery:

var found = false; 
var search = 'something not in the list'; 
$("#drop").children().each(function() { 
    if($(this).html() == search) { 
     found = true; 
     $(this).attr('selected', true); 
     return; 
    } 
}); 
if(!found) { 
    var nextValue = $("#drop").children(":last").val() + 1; 
    $("#drop").append('<option value="' + nextValue + '">'+search+'</option>'); 
    $("#drop").children(":last").attr('selected', true); 
} 

http://jsfiddle.net/Zhk5w/1/

相關問題