Samsul Arifin
Samsul Arifin

Reputation: 243

How to get Selected Index JQuery Mobile Listview

New Bie : I have a list data that get from database using json format and display into listview. But i still confuse how to get the selected index of the listview, this is my code :

<script>
    function loadListTips(){
    $('#message').html('Loading...');
    $.ajax({
        type: 'get',
        url: "http://10.0.2.2/compfest/ajax/belajar/list_tips.php",
        success: function(response){
            var html = '';
            $.each(response, function(index,item){
                html += '<li>';
                html += '<a>';
                html += '<span class="judul">' + item.judul + '</span>';
                html += '</a>';
                html += '</li>';
            });
            $('#penyakit_list').html(html);
            $('#penyakit_list').listview('refresh');
            $('#message').html('');
        },
        error: function(e){
            alert('Error: ' + e);
        }
    });
}
</script>

Hope there is someone help me.

Upvotes: 2

Views: 2983

Answers (2)

efkan
efkan

Reputation: 13227

+1 goes to bundleofjoy!

I can't add a comment because my "reputation point" below the limit value to add comment.

I used this answer as alert($(this).closest("li").attr("id"));

Have a good day!

Upvotes: 1

krishwader
krishwader

Reputation: 11381

You don't need selected index of the li to bind the click event. You could try using event delegation to bind your click events. Bind the click event to the ul and delegate it to li.

$("#penyakit_list").on("click", "li a", function() {
  //your code
}); 

One more option would be to bind the click to the document :

$(document).on("click", "#penyakit_list li a", function() {
  //your code
}); 

To access the index, just use this inside the click event :

$(this).closest("li").index();

where this is the a you just clicked. So now your click event would look like this :

$(document).on("click", "#penyakit_list li a", function() {
      alert($(this).closest("li").index()); // this will give the index of the li. You could store it in a variable and send it via ajax.
}); 

Upvotes: 4

Related Questions