KJS
KJS

Reputation: 1214

jQuery .each returns only first result

This script gives me the first 'id' for every result found on click and alert. It is an ajax live result and the code returns all the right values.

Puzzling here on why the alert only shows the first record from the live result, when clicking each of them.

$(document).on( "click", ".result_list", function() {
    $(".result_list").each(function(){
        var mainID = $(".result_list").attr('id');
        alert(mainID);
    });
});

The code generated is:

<div class=\"result_list\" id=\"$c1-$c2-$c3\">the content per line is correct</div>
(up to X, and all with different data)

Upvotes: 0

Views: 66

Answers (2)

Wilfredo P
Wilfredo P

Reputation: 4076

Uses $(this) inside .each() becouse you are getting only the first item:

$(document).on( "click", ".result_list", function() {
        var mainID = $(this).attr('id');
        alert(mainID);
});

Update:

How you a looking for the .result_list clicked, remove the .each()

Upvotes: 2

kefy
kefy

Reputation: 535

Try to change this

var mainID = $(".result_list").attr('id');

to

var mainID = $(this).attr('id');

Upvotes: 1

Related Questions