Reputation: 2614
I have a list:
<ul id="list">
<li class="one">Item A</li>
<li class="one">Item B</li>
<li class="two">Item C</li>
<div id="pressed">Submit</div>
</ul>
and when "Submit" is pressed I want to retrieve the value of the list item which has a class of "two". In this instance, pressed Submit would return "Item C". Here's the jQuery I've tried:
$("#pressed").click(function() {
var v = $('#list').filter('.two').val();
alert(v);
});
But all this returns is 0
. What's the best way to do this? Only one <li>
will have a class of "two" at any one time.
Upvotes: 2
Views: 12988
Reputation: 3626
After Rory McCrossan's correction with HTML you can do this.
$("#pressed").click(function() {
alert($('#list .two').text());
});
Upvotes: 1
Reputation: 148110
You need html() or text() instead of val(). The function val() is used for input elements like text, checkbox etc. Also put div outside ul to make your html valid as Rory McCrossan pointed
var v = $('#list').filter('.two').html();
Upvotes: 2
Reputation: 337560
Firstly, your HTML is invalid as div
elements cannot be children of ul
:
<ul id="list">
<li class="one">Item A</li>
<li class="one">Item B</li>
<li class="two">Item C</li>
</ul>
<div id="pressed">Submit</div>
Secondly, text()
is the property you want, not val()
:
$("#pressed").click(function() {
var v = $('#list').find('.two').text();
alert(v);
});
Upvotes: 8