[英]Selecting a value in drop down list using javascript
A]問題摘要:
嘗試在頁面加載時預先選擇用戶所在國家/地區
B]詳情:
1]我正在使用maximinds javascript找出一個用戶縣。
2]我有一個下拉列表,其中包含225個左右的國家/地區的列表。
3]在我的HTMLr頁面的javascript部分,我試圖從下拉列表中選擇用戶國家/地區。
但這個國家沒有被選中
C]代碼摘錄:
<select name="country_name" id="id_country_name">
<option value="" selected="selected">---------</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Aring land Islands">Aring land Islands</option>
</select>
<!-- including the geoip javascript library -->
<script src="http://j.maxmind.com/app/geoip.js" type="text/javascript"></script>
<!-- By default, we will select users country -->
<script type="text/javascript" language="JavaScript">
document.getElementById(geoip_country_name()).selected = true
</script>
謝謝,
[編輯#1]
嘗試了以下jquery代碼,但這不會填充下拉列表:
<!-- including the geoip javascript library -->
<script src="http://j.maxmind.com/app/geoip.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("option[value='" + geoip_country_name() + "']").attr('selected', 'selected');
});
</script>
[編輯#2]
試過$(“#id_country_name”)。val(geoip_country_name());
<div id="userDataForm">
<form method="POST" action="/UserReporting">
<table>
<!-- Printing the forms for users country, city -->
<tr><th><label for="id_country_name">Country name:</label></th><td>
<select name="country_name" id="id_country_name">
<option value="" selected="selected">---------</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Aring land Islands">Aring land Islands</option>
<option value="Albania">Albania</option>
</select>
</td></tr>
<tr><th>
<label for="id_city_name">City name:</label></th><td><input type="text" name="city_name" id="id_city_name" /></td></tr>
</table>
<input type="submit" name="report_up" value= "Report Up">
<input type="submit" name="report_down" value= "Report Down">
</form>
<!-- including the geoip javascript library -->
<script type="text/javascript" language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script src="http://j.maxmind.com/app/geoip.js" type="text/javascript">
</script>
<script type="text/javascript">
$(function () {
$("#id_country_name").val(geoip_country_name());
});
</script>
嘗試
document.getElementById('id_country_name').selectedIndex=index;
其中index是對應於所需選擇的整數。
document.getElementById
調用僅在HTML中的每個<option>
都具有國家/地區名稱(用“_”或類似內容替換空格)時才有效:
<select name="country_name" id="id_country_name">
<option value="" selected="selected">---------</option>
<option id="Afghanistan" value="Afghanistan">Afghanistan</option>
<option id="Aring_land_Islands" value="Aring land Islands">Aring land Islands</option>
</select>
但是,我傾向於使用jquery這種方法,因為它不需要為每個選項提供自己的id:
$(function () {
$("#id_country_name").val(geoip_country_name());
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.