Dejan Biljecki
Dejan Biljecki

Reputation: 605

Weird JQuery-AJAX append/text/html

I have a JQ-AJAX function that retrieves some results, and then on success it should make a list and add it to an element. I create an UL based on the results - here is the success function:

success: function (info) {
        var shipActionsUL = '<ul class="shipActionsList>';

        $(info).find('string').each(function (index) {
            var action = $(this).text();
            shipActionsUL += '<li id="'+action+'">'+action+'</li>';

        });

        shipActionsUL += '</ul>';
        $('#hello').text(shipActionsUL);

    }

Now, when the text of #hello changes, the result is:

<ul class="shipActionsList>
    <li id="aaMove">aaMove</li>
    <li id="aaAttack">aaAttack</li>
</ul>

Which is what I want the UL to look like in the DOM. However this is the literal text. When I try to actually make the list with $('#hello').html(shipActionsUL); I get a weirdly formated UL - its first List Item missing its bullet, and it looks like this when I inspect the list:

<ul class="shipActionsList>
    <li id=" aamove">aaMove</li>
    <li id="aaAttack">aaAttack</li>
</ul>

Notice the id of aamove - lower case and the extra space before it. Regardless of the List items in the list, it's always the first element that is messed up.

Also, if I would remove the ID from the list items having only

   shipActionsUL += '<li>'+action+'</li>';

A list would not appear in the #hello at all on $('#hello').html(shipActionsUL);

The XML response - info from success - would be in this format (now only aaAttack would be messed up):

<?xml version="1.0" encoding="utf-8"?>
 <ShipActions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
 <shipID>162</shipID>
 <Actions>
    <string>aaAttack</string>
    <string>aaMove</string>
    <string>aaSttack</string>
 </Actions>
 </ShipActions>

Upvotes: 1

Views: 319

Answers (2)

Bill Criswell
Bill Criswell

Reputation: 32921

It's very strange that there's no space before the text node of the first list item. What if you do:

var action = $.trim($(this).text());

Upvotes: 0

p e p
p e p

Reputation: 6674

I think it's because you are missing a closing quote on the UL tag:

var shipActionsUL = '<ul class="shipActionsList">'; //Previously missing closing double quote.

Also, if you don't want the ID to contain the extra space, you can trim the action:

var action = $(this).text().trim();

Upvotes: 2

Related Questions