我正在将Postcode与我的网络项目集成在一起。我正在使用县/州的下降。邮政编码随处返回郡的名称。当我只有名字时,我可以更改选定的索引吗? (我正在使用与数据库字段相关的值字段的数字。)
我尝试了以下内容:
var f = document.getElementById("state_dropdown");
f.options.[f.selectedIndex].text = response[0].County;
我试图在这里包含下拉代码html,但由于某些原因我无法使其正常工作。
但当然这只会更改已选中的下拉列表中的项目的文本字段。
我可以查询数据库并找出我为该县分配的ID,但是如果有其他方法,我宁愿不知道。
答案 0 :(得分:2)
循环选项,直到匹配为止:
for (var i = 0; i < f.options.length; i++) {
if (f.options[i].text == response[0].Country) {
f.options.selectedIndex = i;
break;
}
}
答案 1 :(得分: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");
答案 2 :(得分: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>