Updating list of <select> options using jquery and ajax

前端 未结 2 907
陌清茗
陌清茗 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 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)

提交回复
热议问题