Jennifer Anthony
Jennifer Anthony

Reputation: 2277

Problem with append in $.each

I have 3 output in following jQuery.each(), i want echo(append) each a of they in one tag li.

Like:

This is output $.each(): how & hello & hi

I want this:

<ol>
    <li>
        <a href="">how</a>
    </li>
    <li>
        <a href="">hello</a>
    </li>
    <li>
        <a href="">hi</a>
    </li>
</ol>

But following jquery code append all 3 times in the a li, as:(i not want this)

<ol>
    <li>
        <a href="">howhellohi</a>
    </li>
    <li>
        <a href="">howhellohi</a>
    </li>
    <li>
        <a href="">howhellohi</a>
    </li>
</ol>

This is my jquery code:

$.ajax({
    type: "POST",
    dataType: "json",
    url: 'get_residence',
    data: dataString_h,
    cache: false,
    success: function (respond) {
        $.each(respond.data, function (index, value) {
            $('ol li').append('<a href="" class="tool_tip" title="ok">' + value.name[index] + '</a>');
        });
    },
    "error": function (x, y, z) {
        alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
    }
});

This is my respond in jquery code:

{
    "data": [{
        "name": "how",
        "star_type": "5-hotel",
        "site": "www.sasaas.assa",
        "service": ["shalo", "jikh", "gjhd", "saed", "saff", "fcds"],
        "address": "chara bia paeen"
    }, {
        "name": "hello",
        "star_type": "4-motel",
        "site": "www.sasasa.asas",
        "service": ["koko", "sili", "solo", "lilo"],
        "address": "haminja kilo nab"
    }, {
        "name": "hi",
        "star_type": "3-apparteman",
        "site": "www.saassaas.aas",
        "service": ["tv", "wan", "hamam", "kolas"],
        "address": "ok"
    }]
}

How can fix it?

Upvotes: 0

Views: 168

Answers (3)

Shadow Wizard
Shadow Wizard

Reputation: 66389

I think this is the logic you're after:

$.each(respond.data, function (index, value) {
    $('ol li').eq(index).append('<a href="" class="tool_tip" title="ok">' + value.name[index] + '</a>');
});

This will add the data to the proper list item, not the same data to all list items.

Upvotes: 1

genesis
genesis

Reputation: 50976

Change

value.name[index] 

in your code to

value.name

because that's actually the correct code. That's actually why you use .each()

Upvotes: 2

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

Your code seems correct to me, the problem might lie in value.name[index] which seems to be always equal to howhellohi. If you alert value.name[index] what do you get?If you get always howhellohi the problem is in your server side function

Upvotes: 0

Related Questions