简体   繁体   English

使用JSON和jQuery填充下拉列表

[英]Populate dropdown with JSON and jQuery

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. 这是在第一个下拉列表的onChange事件发生的,但是当我从下拉列表1中选择一个选项时我遇到了问题,然后它执行getJson并且它在JSON中返回正确的值,但是问题是即使我选择了相同的值。

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: 返回的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: dropdown1在第一个onChange事件上具有正确的值,但是在它开始重复值之后:

Example: I have 2 Hardware support, 2 test ... and it just goes to add on it. 示例:我有2个硬件支持,2个测试...,然后添加它。

在功能开始时,删除现有选项

$('#id_category').empty();

You need to remove all options before adding the new options. 在添加新选项之前,您需要删除所有选项。 Before your for loop, add the following: 在for循环之前,添加以下内容:

$("#id_category").find("option").remove();

This should remove the current items and make room for the new ones. 这应该删除当前项目,并为新项目腾出空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM