views:

61

answers:

5

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?

A: 

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

Nick Allen - Tungle139
Won't that tell you how many `li`s there are within the `ul`, rather than the index of the clicked-on `li` within the `ul`?
Dominic Rodger
Err yes, sorry I meant preceding-siblings
Nick Allen - Tungle139
@Nick - I don't think preceding-siblings is valid jQuery - am I missing something? Do you mean `prevAll` (http://api.jquery.com/prevAll/)?
Dominic Rodger
Yes exactly, I said that the post wasn't 100% syntactically correct but the concept works, all the OP has to do is check the jquery api for the correct syntax
Nick Allen - Tungle139
A: 
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
}
Praveen Prasad
this doesn't even do what Ad Taylor asked...
Kennethvr
@keeth this code will solve his problem
Praveen Prasad
+7  A: 

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.

Sinan Y.
perfect thanks!!!
Ad Taylor
@Ad, you're welcome, @Dominic, thanks for the edit...
Sinan Y.
+2  A: 

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

c0mrade
Without an id on the `ul`, this almost certainly won't do what he wants (see my answer).
Dominic Rodger
@Dominic Rodger yes I saw your answer, well he got what he asked for .. so I'm not going to bother updating a question .. tnx for pointing that out to me though .. it might just be to me sometime soon
c0mrade
+2  A: 
$("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 lis within uls, which is not what you want.

Dominic Rodger