In my html template I've got a label with an input radio inside:
<label id="myid" class="inline">
<input type="radio" value ="11">
my text
</label>
I need to change the text of the label with jquery. I tried this:
$('#myid').html('my new text');
or
$('#myid').text('my new text');
but when I do that I lose my input radio. How can I preserve the input radio inside the label and modify label's text?
There are two ways to pair a label and an input. One is by wrapping the input in a label (implicit), and the other is by adding a for attribute to the label and an id to the input (explicit). Think of an implicit label as hugging an input, and an explicit label as standing next to an input and holding its hand.
Nesting inputs inside of the label is accepted practice. The w3c wiki site even provides an example. w3.org: The label element may contain at most one descendant input element, button element, select element, or textarea element.
Associating a <label> with an <input> element offers some major advantages: The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too.
Try this:
$('#myid').contents().last().replaceWith('my new text');
Put your text in a span
and try this:
<label id="myid" class="inline">
<input type="radio" value ="11">
<span>my text</span>
</label>
$('#myid').find("span").text('my new text');
Check JSFiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With