JQuery $ (this) .val returns 0
I have a simple list:
<ul id="large_box_custom_list"> <li id="8" class="large_box">Item 1</li> <li id="13" class="large_box">Item 2</li> </ul> then I have a jQuery function as follows:
$(function() { $('li.large_box').css('cursor', 'pointer') .click(function() { var show_id = $(this).val(); alert(show_id); }); }); When I click on the list items, my appearance shows a value of 0, when I expect a value of 8 or 13.
Because you must use the standard element DOM id property . jQuery .val() has nothing with element id.
$('li.large_box').css('cursor', 'pointer').click(function () { var show_id = this.id; alert(show_id); }); You are doing it wrong.
The id attribute is intended to be used as a unique identifier, and not as a means of storing data.
In addition, .val() intended for use in input, select, textarea elements to access their current values.
If you need an element attribute, use the .attr() function.
If you need to store data in an element, use your own HTML5 data- element:
<li data-id="8"... <li data-id="13"... Then you can access the value using the .data() function:
var listItemIdentifier = $(this).data('id'); console.log( listItemIdentifier ); //should output 8 or 13 depending on which you click on The id attribute is not a value attribute.
You can set it to get the id:
$(this).attr("id"); Or set the value in HTML
<li id="8" value="8" class="large_box">Item 1</li> Here is a live example: http://jsfiddle.net/BBm4R/