I am trying to find out how to find the position that an item appears in a list. For example:
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
If I clicked on item 2, I would want to receive '2'. Is this possible?
It's possible by using jquery's index.
EDIT:
<ul id="my_list">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
and in js,
var $my_list = $('#my_list');
$my_list.find('li').click(function(){
var index = $('ul#my_list li').index(this);
alert(index);
});
this should do what you need.
hope it helps, Sinan.
you could assign them IDs like
<ul>
<li id="1">item 1</li>
<li id="2">item 2</li>
<li id="3">item 3</li>
</ul>
then :
$("li").live('click', function(){
alert($(this).attr("id"));
}
or without IDs as Sinan says:
$("li").live('click', function(){
alert($("li").index(this) + 1);
}
+1 because indexing starts from 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With