如何通过jQuery选择哪个收音机?
我有两个单选按钮,想要发布所选单词的文本,如何用jQuery获取文本?
我知道如何获取所选单选按钮的值:
$('[name="topping"]:checked').val()
<div>
<label>Would you like extra topping?</label>
<input type="radio" value="y" name="topping" id="toppingy"/><label for="toppingy"
class="sidelabel">Yes</label>
<input type="radio" value="n" name="topping" id="toppingn"/><label for="toppingn" class="sidelabel">No</label>
</div>
但这不起作用:
$('[name="topping"]:checked').text()
答案 0 :(得分:1)
答案 1 :(得分:0)
元素复选框没有任何文字 - 您可以通过工作区解决问题 - 例如标题标签 - 或收音机后的<span>
。
HTML:
<input class="radio" type="radio" title="testname" name="testme"><br>
<input class="radio" type="radio" title="testname2" name="testme">
JQ:
$('.radio').on('change', function(){
var names = $(this).attr('title');
alert(names);
});
工作示例:
修改:使用代码的工作示例(添加了一个类):
$('.topping').on('change', function(){
var names = $(this).next('label').text();
alert(names);
});
答案 2 :(得分:0)
我修改了您的HTML,您有一组相关选项,因此我已将广播输入包装在<fieldset>
中并使用<legend>
元素提供相关信息指示选项与哪些内容相关(<label>
是将特定文本与特定表单元素(<input>
,<select>
,<textarea>
)关联,而不是通用标签/前往一个小组。那就是说,我建议:
// selecting the <input> elements of 'type="radio"',
// using on() to bind a change-event handler:
$('input[type=radio]').on('change', function() {
// this is the newly-checked radio <input>,
// here we get the text of the next-element:
var text = this.nextElementSibling.textContent;
console.log(text);
});
$('input[type=radio]').on('change', function() {
var text = this.nextElementSibling.textContent;
console.log(text);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<legend>Would you like extra topping?</legend>
<input type="radio" value="y" name="topping" id="toppingy" />
<label for="toppingy" class="sidelabel">Yes</label>
<input type="radio" value="n" name="topping" id="toppingn" />
<label for="toppingn" class="sidelabel">No</label>
</fieldset>
&#13;
或者,在兼容的浏览器中,我们可以从特定的DOM结构中抽象出来,并使用labels
属性,该属性返回与特定元素相关的<label>
元素的NodeList:
$('input[type=radio]').on('change', function() {
// getting NodeList containing the related <label> elements:
var relatedLabels = this.labels,
// if there are any labels associated, we get the text
// of the first <label>, otherwise we use an empty string:
text = this.labels.length ? this.labels[0].textContent : '';
console.log(text);
});
$('input[type=radio]').on('change', function() {
var relatedLabels = this.labels,
text = this.labels.length ? this.labels[0].textContent : '';
console.log(text);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<legend>Would you like extra topping?</legend>
<input type="radio" value="y" name="topping" id="toppingy" />
<label for="toppingy" class="sidelabel">Yes</label>
<input type="radio" value="n" name="topping" id="toppingn" />
<label for="toppingn" class="sidelabel">No</label>
</fieldset>
&#13;
答案 3 :(得分:-1)
$("input[name='topping']:checked").val()
&#13;