Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $(this).val returns 0

Tags:

jquery

I have a simple list like this:

<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 like this:

$(function() { 
$('li.large_box').css('cursor', 'pointer')
.click(function() {
    var show_id = $(this).val();
    alert(show_id);
    });
});

When I click the list items my alery shows a value of 0 when I am expecting a value of 8 or 13.

like image 411
JackBurton Avatar asked Sep 20 '11 18:09

JackBurton


People also ask

What is .VAL in jQuery?

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.

How to Get value of an element in jQuery?

jQuery val() method is used to get the value of an element. This function is used to set or return the value. Return value gives the value attribute of the first element. In case of the set value, it sets the value of the attribute for all elements.

What does val() method do?

val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined . When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .


1 Answers

Because you should be using the standard DOM element id property. jQuery's .val() method has nothing to do with an element's ID.

$('li.large_box').css('cursor', 'pointer').click(function ()
{
    var show_id = this.id;
    alert(show_id);
});
like image 129
Matt Ball Avatar answered Oct 29 '22 03:10

Matt Ball