2012-04-13 85 views
3

我將Postcode與我的web項目集成在一起。我正在使用縣/國家/地區字段的下拉菜單。任何地方的郵政編碼都會返回縣的名稱。當我只有名字時,我可以更改選定的索引嗎? (我正在使用與數據庫字段相關的值字段的數字)。如何更改所選索引當我只有名稱?

我試過如下:

var f = document.getElementById("state_dropdown"); 
f.options.[f.selectedIndex].text = response[0].County; 

我一直在努力,包括下拉這裏代碼HTML,但我不能讓它出於某種原因正常工作。

但是,當然這只是改變了已經選擇的下拉菜單中的項目的文本字段。

我可以查詢數據庫,找出我已經分配了哪個ID,但是如果有另一種方法,我寧願不要。

+0

不是100%肯定我得到你想要的。通過只改變選定的索引名稱,你是否意味着選項標籤的內容(可見的字符串選項)? – GillesC 2012-04-13 11:41:11

回答

2

環比選項,直到你有一個匹配:

for (var i = 0; i < f.options.length; i++) { 
    if (f.options[i].text == response[0].Country) { 
     f.options.selectedIndex = i; 
     break; 
    } 
} 

Demo.

2

我會做一個函數,遍歷標籤:

參見:http://jsfiddle.net/Y3kYH/

<select id="country" name="countryselect" size="1"> 
<option value="1230">A</option> 
<option value="1010">B</option> 
<option value="1213">C</option> 
<option value="1013">D</option> 
</select>​ 

JavaScript

function selectElementByName(id, name) { 
    f = document.getElementById(id); 
    for(i=0;i<f.options.length;i++){ 
     if(f.options[i].label == name){ 
      f.options.selectedIndex = i; 
      break; 
     } 
    } 
} 
selectElementByName("country","B"); 
1

只是對其他答案的變化:

<script type="text/javascript"> 

function setValue(el, value) { 
    var sel = el.form.sel0; 
    var i = sel.options.length; 
    while (i--) { 
    sel.options[i].selected = sel.options[i].text == value; 
    } 
} 

</script> 
<form> 
<select name="sel0"> 
    <option value="0" selected>China 
    <option value="1">Russia 
</select> 
<button type="button" onclick="setValue(this, 'Russia');">Set to Russia</button> 
<input type="reset"> 
</form> 
相關問題