Search code examples
jqueryhtml-listsappendto

jQuery Remove LI elements inside UL


I am trying to fetch stores depending on the state the user Selects from a drop down.

<select name="addressInput" id="state" class="mx-stateSelect" onchange='getRetailers()'>
    <option value=""> Choose State</option>
    <option value="Alberta"> Alberta Canada</option>
    <option value="Alaska"> Alaska </option>
    <option value="Alabama">Alabama</option>
    ...
    <option value="Washington"> Washington </option>
</select>

jQuery Function

function getRetailers() {
    var state = $('#state').val();
    var searchUrl = 'getRetailers.php?state=' + state;

    $.getJSON(searchUrl, function(data) {
        var items = [];

        $.each(data, function(key, val) {
            items.push('<li id="' + val.id + '"><a href="#" data-lat="' + val.lat + '" data-lng="' + val.lng + '">' + val.name + '<br/>' + val.address + ', ' + val.city + ', ' + val.zipcode + ' ' + val.stab + '</a></li>');
        });


        $('<ul/>', {
            'class' : 'mx-retailers',
            html : items.join('')
        }).appendTo('.mx-retailerResult');
    });
}

This is adding another set of UL LI to the code. Where as i want to replace the old LI with the new LI i fetch from the database.

HTML Code

<div class="mx-retailerResult">
    <ul class="mx-retailers">
    </ul>
</div>

I want to remove all the LI Element inside the UL and replace it with Fresh content from the database


Solution

  • $('<ul/>', {
        'class' : 'mx-retailers',
        html : items.join('')
    }).appendTo('.mx-retailerResult');
    

    the above code creates a new ul element try

    $('ul.mx-retailers').html(items.join(''));