Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change a label text without interfering with an input radio inside the label?

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?

like image 294
kiks73 Avatar asked Aug 18 '14 16:08

kiks73


People also ask

Can I use input inside label?

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.

Should I nest input in label?

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.

What is the advantage of associating a label with an input 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.


2 Answers

Try this:

$('#myid').contents().last().replaceWith('my new text');
like image 199
antyrat Avatar answered Oct 05 '22 23:10

antyrat


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

like image 28
Moshtaf Avatar answered Oct 06 '22 01:10

Moshtaf