I am trying to populate a dropdown menu from another dropdown.
This happened with the onChange
event of first dropdown but I have problem when I select one of the options from dropdown 1 then it do getJson
and it returns correct values in JSON, but the problem is that dropdown is populated every time even if I select the same value.
Here is the code:
$.getJSON("ajax.php",
{ m: "modules/json/json-get-category",
r: $('#id_project').has('option').val()
},
function(data){
var html = '';
var len = data.length;
alert(len);
//$('#id_category').val('').trigger('chosen:updated');
for (var i = 0; i< len; i++) {
html += '<option value="' + data[i].id + '">' + data[i].catName + '</option>';
}
$('#id_category').append(html);
});
Returned JSON:
[
{"id":"27","catName":"Hardware support"},
{"id":"29","catName":"test"}
]
The dropdown1 has correct value on first onChange event, but after it starts to duplicate values:
Example: I have 2 Hardware support, 2 test ... and it just goes to add on it.
在功能开始时,删除现有选项
$('#id_category').empty();
You need to remove all options before adding the new options. Before your for loop, add the following:
$("#id_category").find("option").remove();
This should remove the current items and make room for the new ones.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.