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
仅当每个 <option>
时,调用才有效在您的 HTML 中,将国家/地区名称作为 id(用“_”或类似内容替换空格):
<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());
});
关于javascript - 使用 javascript 在下拉列表中选择一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5546156/