1

Here's main part of html:

 <div id="table"> <div class="table_item">asd</div> <div class="table_item">asd</div> <div class="table_item">asd</div> </div> 

And JS (JQuery):

$(document).ready( function() { $(".table_item").click( function() { alert($("#table").index($(this))); }); }); 

click handling works but I ALWAYS get -1 from .index.

trying simply $(this).index(); shows the same result.

Please help! What's wrong with the code?

0

3 Answers 3

6

Do this instead:

$(document).ready( function() { var ti = $('.table_item'); ti.click( function() { alert(ti.index(this)); }); }); 

EDIT: Someone had a post that was deleted that was correct, and I think a little better than my code above:

$(document).ready( function() { $('.table_item').click( function() { alert($(this).index()); }); }); 

Working examples of both solutions: http://jsfiddle.net/FishBasketGordo/rx5e7/

Sign up to request clarification or add additional context in comments.

Comments

1

You need to call index on a collection, in this case divs with class table_item

alert($(".table_item").index(this)); 

Comments

1

Since you are attaching a click() listener to $(".table_item"), you can reference the object by using $(this).

Try:

$(document).ready( function() { $(".table_item").click( function() { alert($(this).index()); }); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.