• Item 1
  • 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.

    +4
    source share
    7 answers

    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); }); 
    +9
    source

    val() does not return an identifier. Instead, you want $(this).attr('id') .

    +3
    source

    Try using attr() instead of val() :

     $(function() { $('li.large_box').css('cursor', 'pointer').click(function() { var show_id = $(this).attr('id'); alert(show_id); }); }); 
    +1
    source

    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 
    +1
    source

    use $(this).attr('id')

    <li> cannot make a difference without using non-standard attributes.

    0
    source
     var show_id = $(this).attr('id'); 
    0
    source

    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/

    0
    source

    All Articles