Updating list of <select> options using jquery and ajax

前端 未结 2 901
陌清茗
陌清茗 2020-12-16 00:47

I am trying to make an html select list of options update according to a selection made on a prior html select object. My jquery is below. This is being called correctly.

相关标签:
2条回答
  • 2020-12-16 00:51

    You can use $.getJSON if your expecting a json response. You might also be able to use $.each() and then simply .append() to the select tag. You can reference this.property inside the .each().

    Something like the following:

    $.getJSON("updateTypes.php?q="+brandName, function(data) {
        $("#Type").html('');
        $.each(data, function(){
            $("#Type").append('<option value="'+ this.value +'">'+ this.name +'</option>')
        )
    })
    

    This would assume your json response is something like the following:

    [ { name : "foo", value : "bar" }, { name : "another", value : "example" } ]

    0 讨论(0)
  • 2020-12-16 01:04

    Your code $("#Type").remove(); removes the select object not its options. The correct way of removing options is:

    $("#Type option").remove();
    

    or

    $("#Type").html('');
    

    The second solution seems to be better as stated here: How to remove options from select element without memory leak?

    There is also an error in the part that adds new options. Your javascript code should be:

    var brandName = $("#Brand").val();
    
    $.get("updateTypes.php?q="+brandName, function(data) {
    
        $("#Type option").remove();
        var typeData = JSON.parse(data);
    
        for (loop=0; loop < typeData.length; loop++) {
            $("#Type").get(0).options.add(new Option(typeData[loop]));
        }
    });
    

    The $('#Type').get(0) method refers to the raw DOM object which has the "options" property that you wanted to use (How to get a DOM Element from a JQuery Selector)

    0 讨论(0)
提交回复
热议问题