How Can I get the text of the selected radio in the radio groups
Asked Answered
P

5

8

as said in the title for example:

<input id="User_Type_0" type="radio" name="User_Type" value="1" checked="checked" />
<label for="User_Type_0">User1</label>
<input id="User_Type_1" type="radio" name="User_Type" value="2" />
<label for="User_Type_1">User2</label>

how can I get the text:User 1

Perseid answered 25/1, 2010 at 13:4 Comment(0)
S
19

$('input:radio:checked').siblings('label:first').html()


UPDATE:

As pointed out by Victor in the comments section the previous selector will always select the first label. The next function should work:

$('input:radio:checked').next('label:first').html()
Subcortex answered 25/1, 2010 at 13:8 Comment(3)
and if the order of the html-elements changes, you are screwed :-)Coadunate
And this always selects the first label in DOM order, not the next one!!Selfsupport
@Victor, you are correct. Thanks for pointing this out. I've updated my answer.Subcortex
C
7

how about this?

var forLabel = $('input:radio:checked').attr("id");
$("label[for='" + forLabel + "']").text();
Coadunate answered 25/1, 2010 at 13:13 Comment(2)
Good general idea, but you'll want to use a different variable name – for is a reserved word.Grata
if there are more than 1 group, you can select which group you need with the name-attribute of the radiobuttonCoadunate
C
4

use .next();

$("input:radio:checked").next().text();
Cyprinodont answered 25/1, 2010 at 13:16 Comment(0)
D
2

This works for me (I'm was using jQuery Mobile):

var value = $(":radio[name=location]:checked").val();
var text = $(":radio[name=location]:checked").prev("label").text();

The DOM for this:

<div id="locations" data-role="controlgroup" class="ui-controlgroup ui-controlgroup-vertical ui-corner-all">
   <div class="ui-controlgroup-controls ">
      <div class="ui-radio">
         <label for="location0" class="ui-btn ui-corner-all ui-btn-inherit ui-btn-icon-left ui-radio-off ui-first-child">1439</label>
         <input type="radio" name="location" id="location0" value="1439">
      </div>
      <div class="ui-radio">
         <label for="location1" class="ui-btn ui-corner-all ui-btn-inherit ui-btn-icon-left ui-radio-off ui-last-child">1440</label>
         <input type="radio" name="location" id="location1" value="1440">
      </div>
   </div>
</div>
Diadelphous answered 11/2, 2014 at 18:41 Comment(0)
W
1

What about using the next Adjacent Selector, +?

$('input:radio:checked + label').text();

Here's a Working Demo

Wivinia answered 27/1, 2010 at 13:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.