Flaashing
Flaashing

Reputation: 771

jQuery .each callback error

I am currently messing with the .each() function in jQuery and I am trying to count all div's with the the id of item and add them to a string.

The problem is, I get a callback error from my jQuery source, which I load from jquery.com's website.

var items = "";
$('div.item').each(function(){ 
    items += $('this').data('id');
});

The error, as seen on firebug;

callback is undefined
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { 

Upvotes: 1

Views: 645

Answers (4)

michel
michel

Reputation: 110

$(this) instead of $('this')?

Check the .data() too. Try .attr() :)

Upvotes: 3

Marek Tuchalski
Marek Tuchalski

Reputation: 489

Try below but I'm not sure what you want to get from it.

var items = 0;
$('div.item').each( function() { 
     items += parseInt($(this).attr('id'));
});

To count id's with id name that starts with xyz- can be counted by below script

$('div[id^=xyz-]').length

Upvotes: 1

ghstcode
ghstcode

Reputation: 2912

The problem is with the .data() method you are using:

var items = "";

$('div.item').each(function(){ 
    items += $(this).attr('id');
});

Upvotes: 3

Rup
Rup

Reputation: 34408

I suspect it's not the each, it's the .data. You probably want

items += $(this).data('id');

i.e. using this as a variable not a quoted string.

Upvotes: 10

Related Questions