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?
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?
Pseudo code
$('ul > li').each(function(el) {
el.ClickEvent(function() {
alert(el.preceding-siblings.count() + 1);
});
});
Something like that anyway, sorry didn't have time to get the syntax spot on
okie i have edited my answer do this
$(function()
{
var _item=1;
$('ul li').each(function(){
var _elm=$(this).attr('_elm',_item);
}).bind('click',_handle);
_item++;
});
function _myClick(e)
{
var _yourValue=$(e.target).attr('_elm');
//this is the value u were looking for
}
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
$("ul#your_ul li").click(function () {
// this is the dom element clicked
var index = $("ul#your_ul li").index(this) + 1;
});
You need to give the ul
you want to do this on an id - otherwise it'll return the index of the li
in terms of all li
s within ul
s, which is not what you want.