带有onchange事件的下拉菜单
我有一个下拉菜单,当用户改变下拉框的选项时,会触发一个叫做onchange
的事件,这时会调用ajax来获取结果并显示出来。这一切都运行得很好。
在我的模板中有以下列表。
Apple
Pineapple
每当用户改变下拉框的值时,结果就会合并在一起。
Orange
Graps
Apple
Pineapple
但是输出的结果应该是这样的。
Orange
Graps
我不知道该怎么做。请帮帮我。这是我的 基础代码。这是我的 电影列表 模板。这是我的 电影排序 模板。还有我的 视图。谢谢 :-)
更新:这是ajax代码。
function sortMovie(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/moviesort/?q="+str,true);
xmlhttp.send();
}
下拉菜单
<select name="category" onchange="sortMovie(this.value)">
<option value="">Choose</option>
{% for category in categories %}
<option value="{{ category.id}}">{{category.name}}</option>
{% endfor %}
</select>
2 个回答
0
如果你在用jQuery来调用ajax,我建议你在使用.change()函数之后,直接用.empty()。
我不知道你的代码是什么样的,但应该类似于下面这个。
$('#id_category').change(function() {
/* Set your string to nothing */
var str = "";
/* once your dropdown is changed, it performs a look and gets the new data */
$("#id_category option:selected").each(function () {
/* Before inserting the new data, empty out all the old items */
$('#id_sub_category').empty();
str += $(this).val();
$.get('{% url gear_category %}', { category: str }, function(data){
$(data).appendTo("#id_sub_category");
});
});
});
希望这对你有帮助。
0
我同意ApPel的看法。
不过,因为你没有使用jQuery...
你要么得一个一个遍历选择框里的选项,然后逐个删除,要么如果纯JavaScript支持的话,你可以试着用JavaScript的语法来模仿jQuery的代码。
不管怎样,你都得在添加新值之前先把旧值删掉。这就是问题所在。