optimizing the jquery in django
- by sankar
I have done the following code which actually dynamically generate the values in the third list box using ajax and jquery concepts. Thoug it works, i need to optimize it. Below is the code i am working on now.
<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>
everything works fine but there is a little problem in my code. (ie) my ajax function calls only when there is a change in the select list 2 (ie) 'id_number_2'. I want to make it call in such a way that which ever select box, the third list box should be updated automatically.
Can anyone please help me on this with a possible logical solution