Rod
Rod

Reputation: 15455

jQuery each not getting to second item in array

I'm not sure why the each iteration is not alerting Table Two value.

$(document).ready(function () {
    Test1([{id:"one",tbl:"Table One"},{id:"two",tbl:"Table Two"}]);
});

function Test1(arrObj) {
                   
    $.each(arrObj,function(idx){
        var thing = $(this);
        alert(thing[idx].tbl); //Not getting to Table Two
    
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Views: 40

Answers (2)

marsh
marsh

Reputation: 1441

You mustn't wrap this into $(). Because this is already a value of each element of the array arrObj. You can do so, and it will be enough, jsFiddle:

function Test1(arrObj) {

    $.each(arrObj,function(){
        alert(this.tbl);
    });
}

Upvotes: 1

Jason Sperske
Jason Sperske

Reputation: 30416

Looking at the documentation for $.each() you can see that a second argument is passed to the callback representing the value of the element. You can use it like this:

$(document).ready(function () {
    Test1([{id:"one",tbl:"Table One"},{id:"two",tbl:"Table Two"}]);
});

function Test1(arrObj) {
                   
    $.each(arrObj, function(idx, thing){
        alert(thing.tbl);
    
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 3

Related Questions