1

I have an ordered list that looks as follows:

<div class="col-md-2 panel panel-default">
    <div class="panel-heading">Species Seen</div>
         <div class="panel-body" style="height: 350px; overflow:auto">
             <ol id="speciesAdded"></ol>
    </div>
</div>

The unordered list starts out empty and the user can add items to it on the page. Or, he/she can click a button and have the list created from entries in a DB. This is the part (hydrating the list) I'm having a problem with. This is my jQuery code that makes an AJAX call and attempts to refresh the list:

$("#refreshButton").click(function () {
    var url = "/FieldTrip/RefreshFieldTripSightingList";
    var fieldTripName = $("#FieldTripName").val();
    var accountRowId = $("#AccountRowId").val();

    /* Clear any existing list */
    $("ol#speciesAdded").empty();

    $.getJSON(url, { accountRowId: accountRowId, fieldTripName: fieldTripName }, function (data) {
        $.each(data, function (i, item) {
            $("ol$speciesAdded").appendTo("li").text(item.species);
        });
    });
});

The AJAX call is being made and I get items back. But, my ordered list, after being cleared, does not refresh with items from the DB.

This is an MVC 5 app.

Randy Minder
  • 47,200
  • 49
  • 204
  • 358

2 Answers2

3
$("ol$speciesAdded").appendTo("li").text(item.species);

the selector $ is wrong, I believe...

// is what you wanted?
$("ol#speciesAdded").appendTo("li").text(item.species);

By the way, if you want to get it refreshed, i would suggest to use empty() before.

$("ol#speciesAdded").empty();

One more tipp, if you use appendTo you will let the DOM rerender every time a new item is added. that is not very performant.

try to get all the html, and then insert it at once.

var items = [];

// in the loop then
items.push('<li>' + text + '</li>');

// insert all at once...
$("ol#speciesAdded").empty().html(items.join(""));
Luke
  • 8,235
  • 3
  • 22
  • 36
1

There cannot be a $ selector. Did you by mistake confused with jQuery and you might wanna change your code from:

$.each(data, function (i, item) {
    $("ol$speciesAdded").appendTo("li").text(item.species);
});

by replacing the $ with an # ID selector:

$.each(data, function (i, item) {
    $("ol#speciesAdded").appendTo("li").text(item.species);
});

And also, before refreshing, you need to clear the previous values. So make this way:

$("ol#speciesAdded").html("");
$.each(data, function (i, item) {
    $("ol#speciesAdded").appendTo("li").text(item.species);
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252