Marius Seheia
Marius Seheia

Reputation: 35

jQuery(this) in each only get the last value

I have this piece of code and the variable toto has the same value in each cells of the array (the other threads say that a scope problem but I use var titi=jQuery(this).text(); and titi=jQuery(this).text();

HTML

<table name='xnnjz'><tr><td>1</td><td>2</td><td>3</td></tr></table>

JavaScript

var i=0;
jQuery("table['name=xnnjz'] tr.child-of-application"+indep+" td").each(function () {
    var titi=jQuery(this).text();
    toto[i]=titi;
    i=i+1;
});
console.log(toto);

In console log :

toto=[3,3,3]

Could you help me?

Upvotes: 0

Views: 837

Answers (2)

Adil
Adil

Reputation: 148150

You have to define the array out side each to access it out side each, Also modify your selector as I could not see any class child-of-application

Live Demo

var i = 0;
var toto = [];
jQuery("table[name=xnnjz] td").each(function() {
    var titi = jQuery(this).text();
    toto[i] = titi;
    i = i + 1;
});

Simplified version of above

Live Demo

var toto = [];
jQuery("table[name=xnnjz] td").each(function(idx, item) {    
    toto[idx] = $(item).text();  
});

You can also use jQuery map()

Live Demo

var toto = jQuery("table[name=xnnjz] td").map(function () {
    return jQuery(this).text();    
});

Upvotes: 4

Jai
Jai

Reputation: 74738

See your issues is here:

jQuery("table['name=xnnjz'] tr.child-of-application"+indep+" td").each(function
 //-----------^----------^---Either remove it or do it like this below

jQuery("table[name='xnnjz'] td").each(function

Upvotes: 0

Related Questions