Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is .index() resolving as a number in this statement while .parent().index() is resolving as a string?

Here is the code, it is referencing a TD and "farmland" is the id of the table:

$("#farmland td").click(function(){
        $("#console").html($(this).index() + 1 + ", " + $(this).parent().index() + 1);
    });

When I click a TD, I am getting 1,01 or 1,11 or 1,21 etc... the number is properly adding for .index() but for .parent().index() it is appending the 1 as if it is a string!

Thought this was very curious, as I expected it to either act one way, or the other, not two different ways!

My first guess may be that it's because my + ", " + is switching it to work as a string?

like image 970
MetaGuru Avatar asked Feb 22 '23 06:02

MetaGuru


1 Answers

It's because JavaScript sees the first index() call returning a number to which it adds the number 1, then you're combining it with a string, so it concatenates the number to the string.

For addition, regardless of strings, use parentheses for isolation of the numbers from the strings:

$("#farmland td").click(function(){
        $("#console").html(($(this).index() + 1) + ", " + ($(this).parent().index() + 1));
    });
like image 134
David Thomas Avatar answered May 04 '23 01:05

David Thomas