frenchie
frenchie

Reputation: 51937

jquery accessing label of input

I have some HTML like this:

<input type="radio" class="MyRadio" name="TheName">
<label for="TheLabel">the text</label>

How do I change the label's text?

Tried

$('#TheLabel').text('My New Text');

It doesn't work. What's the way to do it?

Thanks.

Upvotes: 0

Views: 254

Answers (5)

Robert Messerle
Robert Messerle

Reputation: 3032

The 'for' attribute is referring to the input, not the label. In order to properly identify the label, the best practice would be to give it an ID. This is a good habit to form as it makes for fast lookups:

HTML:

<input type="radio" class="MyRadio" name="TheName">
<label for="TheName" id="TheLabel">the text</label>

jQuery Selector:

$( '#TheLabel' )

However, if you wanted to grab an element by the for attribute, using the original HTML, you could do so like this:

$( 'label[for=TheLabel]' )

Upvotes: 0

Michael Zaporozhets
Michael Zaporozhets

Reputation: 24526

use an id for referencing the label which will allow for simpler jquery manipulation

You can then go and change the inside of the tag with whatever you please with the jquery .html() or if you continue to simply just require text manipulation, the .text() function will produce the same results.

Here is a jsfiddle showing an example of your desired outcome: here

The HTML:

<input type="radio" class="MyRadio" name="TheName">
<label id="mylabel" for="TheLabel">the text</label>​

The Jquery:

$('#mylabel').text('My New Text');​

OR

$('#mylabel').html('My New Text');​

Upvotes: 1

scottheckel
scottheckel

Reputation: 9244

Update: looking at @Mark's answer... your code is wrong. The "for" attribute should point to the input. I have cleaned up the answer to fix this.

Match on the attribute equally something and not the #id of the textbox (the label doesn't have an id).

<input type="radio" class="MyRadio" name="TheName" id="TheName">
<label for="TheName">the text</label>​​​​​​​​​​​

$('label[for="TheName"]').text('This is my new text');​

Check out a jsFiddle of it working in action on your HTML.

Upvotes: 0

Mark Brittingham
Mark Brittingham

Reputation: 28865

You've got a few things turned around here. The "for" doesn't identify the label, it identifies the control you are labeling. You'll need to use the "for" correctly and you'll need to give it an ID:

<label for="TheName" id="TheLabel">The Label Text</label>

Then:

$('#TheLabel').text('My New Text');

will work.

Upvotes: 2

DarkAjax
DarkAjax

Reputation: 16223

You're using the wrong selector (in this case treating TheLabel as if it were an ID), you can use something like:

$('label[for=TheLabel]').text('My New Text');​​​

You can also change the for for an id to make the code you already have functional.

Upvotes: 0

Related Questions