0

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

pbaris
  • 4,525
  • 5
  • 37
  • 61
Harsha M V
  • 54,075
  • 125
  • 354
  • 529

3 Answers3

1

This block of code you have is creating a new UL element with a class of mx-retailers:

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

If you dont want to do this then replace it with the following:

items.join('').appendTo('.mx-retailerResult');

This will add all of your li elements into the ul with the class of mx-retailerResult

Dave Haigh
  • 4,369
  • 5
  • 34
  • 56
1
$('<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(''));
pbaris
  • 4,525
  • 5
  • 37
  • 61
1
$('.mx-retailerResult').html($('<ul/>', {
    'class' : 'mx-retailers',
    html : items.join('')
}));
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164