a
  • b
  • c
  • d
  • the I want get the value proper" /> a
  • b
  • c
  • d
  • the I want get the value proper" /> a
  • b
  • c
  • d
  • the I want get the value proper"/>

    Why the jquery prop() method can not get the the element's value property

    2.1k Views Asked by At

    I have several li element in page:

    <li value="a">a</li>
    <li value="b">b</li>
    <li value="c">c</li>
    <li value="d">d</li>
    

    the I want get the value property when hover on it:

    $(function () {
        $('li').live('mouseover', function () {
            console.log($(this).prop('value'));                             
        })
    });
    

    but the result is always 0,then I try the attr() method, it still can not work ,how can I solve this problem?

    5

    There are 5 best solutions below

    0
    Jamiec On BEST ANSWER

    li elements do not have a value property.

    For storing your own meta-data against an element you should use HTML5 data-* attributes:

    <li data-value="a">a</li>
    <li data-value="b">b</li>
    <li data-value="c">c</li>
    <li data-value="d">d</li>
    

    Then use the jquery .data() method to retrieve them:

    $(function () {
        $('li').live('mouseover', function () {
            console.log($(this).data('value'));                             
        })
    });
    
    0
    Mathew Thompson On

    Hmmm, I replicated this in a fiddle, even doesn't work using .val either. Probably because value is only designed for form fields. A solution is to change the value to a data attribute, like so:

    <li data-value="a">a</li>
    <li data-value="b">b</li>
    <li data-value="c">c</li>
    <li data-value="d">d</li>​
    
    $(function () {
        $('li').live('mouseover', function () {
            alert($(this).data("value"));                             
        });
    });​
    

    Try this Fiddle

    0
    Mattias Buelens On

    A <li> element cannot have a value attribute. If you want to define your own custom attributes, prefix them with data-.

    <li data-value="a">a</li>
    <li data-value="b">b</li>
    <li data-value="c">c</li>
    <li data-value="d">d</li>
    

    Then change the name in your JavaScript code:

    $(function () {
        $('li').live('mouseover', function () {
            console.log($(this).prop('data-value'));                             
        });
    });
    

    jQuery also lets you easily access data- attributes using $.data().

            console.log($(this).data('value'));
    
    0
    Kabilan S On

    Instead You can do this

    $(function () 
    {
        $('li').hover( function () {
            console.log($(this).attr('value'));                             
        })
    });
    
    0
    Kabilan S On

    It Works Checked !!

    $(function ()
    {
        $('li').hover( function () {
            alert($(this).text());                             
        })
    });