shyamshyre
shyamshyre

Reputation: 549

How to get the index of the element selected in ListView JQUERYMOBILE

I have created a dynamic listview with a link with id="a".

<ul id="accpmenu" data-role="listview" >
</ul>

$("#accpmenu").append('<li><a href='+ "#" + ' id="a" ">'+ this.textContent +'</a>  </li>');

Now i want to identify the index of the element that I have clicked from this listview.

$("#a").live("click",function(e)
{
    //What should i write here to get the selected index?.
}

I want the index number based on this I need to load the dynamic XML.

Please help me in resolving this.

Thanks Shyam

Upvotes: 2

Views: 10935

Answers (1)

Jasper
Jasper

Reputation: 75993

$('#accpmenu').on('click', ' > li', function () {
    var selected_index = $(this).index();
});

Here is a demo: http://jsfiddle.net/w2JZU/

This will bind an event handler to the list-items in the #accpmenu list for the click event that finds the index of the clicked list-item (compared to other list-item elements).

On a side-note you have what appears to be some invalid HTML in your code:

$("#accpmenu").append('<li><a href='+ "#" + ' id="a" ">'+ this.textContent +'</a>  </li>');

Should change to (notice the removed double-quote after the id attribute):

$("#accpmenu").append('<li><a href='+ "#" + ' id="a">'+ this.textContent +'</a>  </li>');

My example above added the click event handler to the li elements since it is easy to ascertain the index of the clicked element but you can also bind to links in the list:

$('#accpmenu').on('click', 'a', function () {

    //this gets the index by finding the first parent list-item element and getting it's index compared do its siblings
    var selected_index = $(this).parents('li').eq(0).index();
});

Note that .on() is new in jQuery 1.7 and in the cases above replaces .delegate() (from earlier versions).

Here are some docs for ya to help explain the above examples:

Upvotes: 7

Related Questions