How to get value and index of list item onClick
event with jQuery?
For example:
<ul id='uItem'>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
$("#myid li"). click(function() { this.id = 'newId'; // longer method using . attr() $(this). attr('id', 'newId'); });
.val()Returns: String or Number or Array Description: Get the current value of the first element in the set of matched elements.
jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.
jQuery get() Method The $. get() method loads data from the server using a HTTP GET request.
If you had set a value attribute for your li:
<ul id='uItem'>
<li value="item1">Item 1</li>
<li value="item2">Item 2</li>
<li value="item3">Item 3</li>
<li value="item4">Item 4</li>
</ul>
, then you can retrieve it using jQuery like this:
$('#uItem li').click(function(){
var $this = $(this);
var selKeyVal = $this.attr("value");
alert('Text ' + $this.text() + 'value ' + selKeyVal);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With