Sandhurst
Sandhurst

Reputation: 1180

get associated radio button label text using javascript

<label for="radio1">
        This Radio Button 1 has a label associated with it.</label>
    <input type="radio" name="Radio" id="radio1" />

above code has a label and radio button , the label is associated with radio button using the for attribute.

I would like to get the label text if user selects/checks the associated radio button.

Upvotes: 0

Views: 8193

Answers (5)

Martlark
Martlark

Reputation: 14581

You can also use:

$("input:radio").click(function() {
   var label_description = this.parentElement.outerText;
   alert( label_description );
} )

Js Fiddle test:

Get the label for a radio

Upvotes: 0

sdleihssirhc
sdleihssirhc

Reputation: 42496

I know this question is months old, and even already has an accepted answer, but every response here uses the prev method. Just wanted to point out that a slightly more robust technique would be using an attribute selector:

$('input:radio').click(function () {
    var txt = $('label[for=' + this.id + ']').text();
    alert(txt);
});

Upvotes: 3

herostwist
herostwist

Reputation: 3968

If your using jquery:

$('input[name="Radio"]').click(function(){ alert( $(this).prev('label').text() ) });

check out this example: http://jsfiddle.net/7FzQ9/

Upvotes: 1

RoToRa
RoToRa

Reputation: 38431

$("input:radio").click(function() {
  // if the label is before the radio button
  alert( $(this).prev("label").text() );
  // otherwise use
  alert( $("label[for='" + this.id + "']").text() );
});

Upvotes: 1

Gaurav
Gaurav

Reputation: 28765

$('input#radio1').prev('label[for=radio1]').text();

Upvotes: 1

Related Questions