我已经完成了以下代码,它实际上使用 ajax 和 jquery 概念在第三个列表框中动态生成了值。虽然它有效,但我需要优化它。下面是我现在正在处理的代码。
<html>
<head>
<title>Comparison based on ID Number</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="/idnumber/" method="post" align= "center">{% csrf_token %}
<p>Select different id numbers and the name of the <b> Measurement Group </b>to start the comparison</p>
<table align = "center">
<tr>
<th><label for="id_criteria_1">Id Number 1:</label></th>
<th> {{ form.idnumber_1 }} </th>
</tr>
<tr>
<th><label for="id_criteria_2">Id Number 2:</label></th>
<th> {{ form.idnumber_2 }} </th>
</tr>
<tr>
<th><label for="group_name_list">Group Name:</label></th>
<th><select name="group_name_list" id="id_group_name_list">
<option>Select</option>
</select>
</th>
</tr>
<script>
$('#id_idnumber_2').change(
function get_group_names()
{
var value1 = $('#id_idnumber_1').attr('value');
var value2 = $(this).attr('value');
alert(value1);
alert(value2);
var request = $.ajax({
url: "/getGroupnamesforIDnumber/",
type: "GET",
data: {idnumber_1 : value1,idnumber_2 : value2},
dataType: "json",
success: function(data) {
alert(data);
var myselect = document.getElementById("group_name_list");
document.getElementById("group_name_list").options.length = 1;
var length_of_data = data.length;
alert(length_of_data);
try{
for(var i = 0;i < length_of_data; i++)
{
myselect.add(new Option(data[i].group_name, "i"), myselect.options[i]) //add new option to beginning of "sample"
}
}
catch(e){ //in IE, try the below version instead of add()
for(var i = 0;i < length_of_data; i++)
{
myselect.add(new Option(data[i].group_name, data[i].group_name)) //add new option to end of "sample"
}
}
}
});
});
</script>
<tr align = "center"><th><input type="submit" value="Submit"></th></tr>
</table>
</form>
</body>
</html>
一切正常,但我的代码中有一个小问题。(即)我的 ajax 函数仅在选择列表 2 (即)“id_number_2”发生变化时调用。我想让它以这样一种方式调用,即无论哪个选择框,第三个列表框都应该自动更新。
任何人都可以通过可能的逻辑解决方案帮助我吗