Tutorial :jQuery li clicked id and value


<ul id='myid' >    <li>Microsoft Office</li>    <li>Microsoft windows XP</li>     <li>Microsoft windows Vista</li>    <li>Microsoft windows 7</li>    <li>Microsoft windows server 2003</li>      </ul>    <input type='button' id='mybutton' value='submit' disabled >    


$("#myid").click(function(){         $("#mybutton").attr("disabled", false);      });    

After clicking on the one of the items in LI, the submit button gets enabled. till now all good. But I don't know how to grab the value of the LI which one was clicked (it is suppose to give the value of the li item after clicking of the submit button)



Here's a solution with .delegate()

$("#myid").delegate('li','click', function(){       alert( $(this).text() );      $("#mybutton").attr("disabled", false);    })​;  

This is sometimes a better option if you're going to have tons of elements to which you want to attach handlers. Instead, you have just one handler sitting a level up, listening for the events triggered on the children within.



$("#myid li").click(function(){       var text= $(this).text(); // will get the actual text of li use .html() if you want tags in there.     alert(text)     $("#mybutton").attr("disabled", false);      });  


LI has no value attribute.

You can add hidden element inside LI to store value. Also you need to catch click on LI, not UL.

<li>Microsft Office<input type="hidden" value="1" name="msoffice" /></li>  

And JS:

$("#myid li").click(function(){      $("#mybutton").attr("disabled", false);      var value = $(this).find('input').val();      alert(value); // 1  });  

And it will be even better if you place INPUT[type=radio] inside LI and add LABEL for text so form will work even without javascript.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »