user3023313
user3023313

Reputation: 124

How to get listview selected id and a href text?

I have a dynamic listview which the id and text are dynamic from server.

For simplicity, let's say something like this:

<ul id="productslist" data-role="listview" data-inset="true">
    <li data-role="list-divider">Products</li>
    <li id="123"><a href="" onclick="check();">#copper 1</a></li>
    <li id="124"><a href="" onclick="check();">#copper 2</a></li>
</ul>

I need the get the list id and product name. (I don't know the id value since it'll be dynamic)

Any suggestions?

    <!DOCTYPE html> 
<html> 
<head> 
    <title>Testing</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
     <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
        <script>

          $(document).on("pageinit","#test1",function(){   

           }); 

         $(document).on("pagebeforeshow","#test1",function(){

          //dynamic list with    


         });

         function check(){
          var href = $(this).attr('href');
          var id = $(this).parent().attr('id');   

         alert('href :'+id+' ,value:'+id);       
        };

         </script>       
</head> 
<body> 

<div data-role="page" id="test1">
     <div data-role="header">
    <h1 style="white-space: normal;margin-left:60px;" id="headertitle"></h1>
            <a href='menu.html'  class='ui-btn-right' data-icon='home' data-theme="a" >Home</a>
    </div><!-- /header -->

        <div data-role="content">
        <h4>List #</h4>

         <ul id="productslist" data-role="listview" data-inset="true">
            <li data-role="list-divider">Products</li>
            <li id="123"><a href="" onclick="check(this);">#copper 1</a></li>
            <li id="124"><a href="" onclick="check(this);">#copper 2</a></li>
            <li id="125"><input type="button" value="#copper 3" onclick="check();"></li>
         </ul>

        <input type="button" onclick="openProduct('data');" value="Click"/>

    </div><!-- /content -->

    <div data-role="footer" data-position="fixed">
        <h4></h4>
    </div><!-- /footer -->

</div><!-- /page -->
</body>
</html>

Upvotes: 0

Views: 1924

Answers (1)

Use .on()

$('#productslist').on('click','a',function(e){
    e.preventDefault();//stop default behavior of anchor tag
    var href = $(this).text();
    var id = $(this).parent().attr('id'); //get parent li id
});


Fiddle Demo

onclick="check(this);"


Put this code in head or at the end of the page

function check(el) {
    var txt = $(el).text();
    var id = $(el).closest('li').attr('id');
    alert('id : ' + id + ' ,  value: ' + txt);
};

Upvotes: 3

Related Questions