I'm trying to get the text of the labels that belong to checked radio buttons, but I can't and my code doesn't work correctly:
$(document).ready(function() { var IS_SEX_Title $('input[name="IS_SEX"]:radio:checked').each(function() { IS_SEX_Title = $(this).parent().find('label').text(); }); alert(IS_SEX_Title) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class="radio-inline" style="margin-right:10px;"> <input value="0" class="form-control psd-input-radio" name="IS_SEX" id="IS_SEX_0" data-top-id="IS_SEX" checked="" type="radio"> male </label>
Try something like this:
$('input[name="IS_SEX"]').parent('label').text();
It will return male
The parent is the label
- remove find()
. Also note that the each()
is redundant as you can only have one checked radio button per named group.
$(document).ready(function() { var IS_SEX_Title = $('input[name="IS_SEX"]:radio:checked').parent().text().trim(); console.log(IS_SEX_Title) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class="radio-inline" style="margin-right:10px;"> <input value="0" class="form-control psd-input-radio" name="IS_SEX" id="IS_SEX_0" data-top-id="IS_SEX" checked="true" type="radio"> male </label> <label class="radio-inline" style="margin-right:10px;"> <input value="0" class="form-control psd-input-radio" name="IS_SEX" id="IS_SEX_1" data-top-id="IS_SEX" type="radio"> female </label>
Just add this $(this).parent().text();
instead of $(this).parent().find('label').text();
because label has text. so you don't need to find label.
See working snippet below:
$(document).ready(function() { var IS_SEX_Title $('input[name="IS_SEX"]:radio:checked').each(function() { IS_SEX_Title = $(this).parent().text(); }); alert(IS_SEX_Title); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <label class="radio-inline" style="margin-right:10px;"> <input value="0" class="form-control psd-input-radio" name="IS_SEX" id="IS_SEX_0" data-top-id="IS_SEX" checked="" type="radio">male</label>
It's not working because you are changing the value inside forEach. Try put the alert inside the foreach then you can access directly by class. Take a look bellow:
var IS_SEX_Title $('input[name="IS_SEX"]:radio:checked').each(function() { IS_SEX_Title = $('.radio-inline').text(); console.log(IS_SEX_Title); alert(IS_SEX_Title); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class="radio-inline" style="margin-right:10px;"> <input value="0" class="form-control psd-input-radio" name="IS_SEX" id="IS_SEX_0" data-top-id="IS_SEX" checked="" type="radio"> male </label>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.