Why the jquery prop() method can not get the the element's value property
Question
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?
Solution
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'));
})
});
OTHER TIPS
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
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'));
Instead You can do this
$(function ()
{
$('li').hover( function () {
console.log($(this).attr('value'));
})
});
It Works Checked !!
$(function ()
{
$('li').hover( function () {
alert($(this).text());
})
});