user2945241 user2945241 - 1 month ago 5
jQuery Question

jQuery indexOf is not working properly

I ran in to this problem, and can't figure out what to do.

I have table:

<table class="jtable">
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>agea</td>
<td>haeh</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>1</td>
</tr>
</tbody>
</table>


And I need to check first column, this is what I do:

$(document).ready(function(){
var arr = new Array(2, 1);
$('.jtable').find("tbody tr").each(function(){
var firstCol = $(this).find("td:first").text();
var inArray = arr.indexOf(firstCol);
alert(firstCol+" "+inArray);
if(inArray == -1){
$(this).css("background", "red");
} else {
$(this).css("background", "green");
}
});
});


But all I get is -1 for all loop cycles from
indexOf
, when I change
indexOf(firstCol)
to one of the numbers in array it works good, but I need dynamic var there. Any Solutions to this, or what I am doing wrong?

Here is the fiddle: http://jsfiddle.net/raa8B/

I tried this with
$.inArray
too

Answer

You are looking for a string in an integer array. You should convert to an int before indexOf

 var inArray = arr.indexOf(parseInt(firstCol));

JSFiddle

Comments