0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

At the beginning of your function, remove the existing options

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.