Reputation: 1241
I have some elements in my document like:
<div class="checkbox-inline"><label><input id="mylabel" value="False" type="checkbox">mytext</label></div>
When I try to get the text using:
$("#mylabel").text();
I get an error that text() is not defined on that object. My ids are unique, so my object is in the 0: position in $("#mylabel")
but both of these return an empty string for the text:
$("#mylabel").first().text();
$("#mylabel")[0].text();
How can I get the text mytext
out of these elements? And how can I programmatically modify it?
I realize now that my problem is slightly different than what I thought it was. Please see: Modifying the text of a label that also contains an input (checkbox) for my follow-up question. Thanks!
Upvotes: 0
Views: 39
Reputation: 105
Its $("#mylabel").html()
to get the inner html of tag.
EDIT:
For your particular case it can be:
$("#mylabel").parent().text();
Upvotes: 0
Reputation: 895
I'm assuming you're trying to access the text of the label element, in this case "mytext"? The reason this isn't working is because the id is on the input element, whcih doesn't actually contain that text
<input id="mylabel" value="False" type="checkbox">
That's the entirety of your input element.
As others have stated, you can get the value of that element using
$("#mylabel").val()
Which will give you "False"
However, if you do need the text "mytext" and don't want to change your markup you can use this
$("#mylabel").parent().text()
Which gets the element with the mylabel id, finds it's parent element (in this case the label element) and then gets the text from that element.
Now that you know that, you might realise that it's easier to just put an id on the label!
Upvotes: 1
Reputation: 21882
If you want the label text.. then you want to use
$('.checkbox-inline label').text();
You're targeting the checkbox itself, not its' label.
Upvotes: 0
Reputation: 350137
The value of an input element is not given by text()
, but by val()
.
If you want to get the label text:
$("#mylabel").parent().text()
It is a bit confusing that you give the id mylabel
to an input
element, which is not the label
element.
Upvotes: 5