[英]get text of label that belongs to checked radio button
我正在尝试获取属于checked
单选按钮的标签text
,但似乎无法完成。
$(document).ready(function(){
$("body").on("click", "#btn", function(){
var radios = $("input[type='radio']");
$.each(radios, function(index, element){
if ($(this).prop("checked") === true){
var radioID = element.id;
$("label").each(function(ind, elm){
if ($(elm).prop("for") == radioID){
console.log($(elm));
}
});
}
});
});
});
无论出于什么原因打印出来
- [11:07:13.834]({0:({}),上下文:({}),篇幅:1})@ http://jsbin.com/uniwum/2/edit:71
在控制台中。 我做错了什么?
这样做: -
$('#btn').click(function() {
$("input[type='radio']:checked").each(function() {
var idVal = $(this).attr("id");
alert($("label[for='"+idVal+"']").text());
});
});
参考现场演示
以下是文档参考: -
尝试这个:
$('#btn').click(function(){
$('table input[type="radio"]').each(function(){
if($(this).is(':checked')){
console.log($(this).parent().next().find('label').text());
}
});
});
更新:由于它们是单选按钮,因此更快的方法是:
$('#btn').click(function(){
console.log( $('table input[type="radio"]:checked').parent().next().find('label').text() );
});
你需要调用.text()
函数来获取元素的文本,如下所示: $(elm).text()
。
在这种情况下,由于elm
已经是DOM节点,因此可以调用plain elm.innerHTML
获得相同的结果。
您可以通过多种方式执行此操作,具体取决于为单选按钮编写的HTML和单选按钮的文本,我看到了可以通过非常少的工作完成的两种方法。
方法1 :将自定义数据属性分配给具有要显示的相同文本的单选按钮。
<input id="radio4" name="radios1" type="radio" value="4" data-value="radio 4" /> radio 4
<input id="radio5" name="radios1" type="radio" value="4" data-value="radio 5"/> radio 5
<input id="radio6" name="radios1" type="radio" value="4" data-value="radio 6"/> radio 6
<input type="button" id="btn" value="Get from data-value" />
有关自定义数据属性的详细信息,请访问: 自定义数据 - *属性
获取文本的脚本:
$(document).on("click", "#btn", function () {
var value = $("input[name=radios1]:checked").attr("data-value");
alert(value);
});
方法2 :转换单选按钮的html,以便为所有这些按钮分配相同的[name]属性,然后为单选按钮放置“label”字段,如下所示
<input id="radio1" name="radios" type="radio"/>
<label for="radio1"> radio 1</label>
<input id="radio2" name="radios" type="radio"/>
<label for="radio2"> radio 2</label>
<input id="radio3" name="radios" type="radio"/>
<label for="radio3"> radio 3</label>
<input type="button" id="btn1" value="Get from Label" />
获取文本的脚本:
$(document).on("click", "#btn1", function () {
var idVal = $('input[name=radios]:checked').attr("id");
$("label[for='"+idVal+"']").text();
//If you have the radio button in HTML table structure write it as below
$('input[name=radios]:checked').parent().find('label').text();
}
希望这可以帮助 :)
$("input[type='radio']:checked").parent().text()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.