想法是通过所有输入字段,当$(this)
有无线电类型时,检查它是否被选中,是否保存其值。如何知道当前元素是否被选中
我知道还有其他的方式来获得所选的单选按钮的值,但我已经通过所有的输入和做类似的事情。
我试图检查选择的属性,$(this).attr('selected')
没有任何运气......我不知道该怎么做。
感谢
想法是通过所有输入字段,当$(this)
有无线电类型时,检查它是否被选中,是否保存其值。如何知道当前元素是否被选中
我知道还有其他的方式来获得所选的单选按钮的值,但我已经通过所有的输入和做类似的事情。
我试图检查选择的属性,$(this).attr('selected')
没有任何运气......我不知道该怎么做。
感谢
对于单选按钮,你应该使用checked
。
$(this).prop('checked')
你可以尝试以下方法:
$(this).is(':radio:checked');
应该是(':radio:checked') –
@FAngel:你说得对。相应地编辑我的帖子。 – DanielB
要检查单选按钮使用的选择:
.prop('checked');
$('input').each(function() {
if(this.type == 'radio') {
console.log($(this).prop('checked')); // or, this.checked
// or, $(this).is(':checked')
}
});
$("input[type='radio']).each(function(){
if($(this).is(":checked")){
// perform your operation
}
});
在代码中缺少双引号。 –
在这里我已经完成了上述查询的完整箱。请检查下面给出的演示链接:
演示:http://codebins.com/bin/4ldqp76
HTML
<div id="panel">
<input type="button" id="btn1" value="Check Selected" />
<p>
<input type="checkbox" value="Checkbox 1"/>
Checkbox1
<br/>
<input type="checkbox" value="Checkbox 2"/>
Checkbox2
<br/>
<input type="checkbox" value="Checkbox 3"/>
Checkbox3
<br/>
<input type="checkbox" value="Checkbox 4"/>
Checkbox4
<br/>
<input type="checkbox" value="Checkbox 5"/>
Checkbox5
</p>
<p>
<input type="radio" name="rd" value="Radio 1"/>
Radio-1
<br/>
<input type="radio" name="rd" value="Radio 2"/>
Radio-2
<br/>
<input type="radio" name="rd" value="Radio 3"/>
Radio-3
<br/>
<input type="radio" name="rd" value="Radio 4"/>
Radio-4
<br/>
<input type="radio" name="rd" value="Radio 5"/>
Radio-5
</p>
</div>
jQuery的
$(function() {
$("#btn1").click(function() {
var SelChk = "Selected Checkbox Values: ";
var SelRad = "Selected Radio Value:";
$("input").each(function() {
if ($(this).is(":checkbox:checked")) {
SelChk += $(this).val().trim() + ", ";
}
if ($(this).is(":radio:checked")) {
SelRad += $(this).val().trim();
}
});
if (SelChk.substr(-2) == ", ") SelChk = SelChk.substr(0, SelChk.length - 2);
alert(SelChk + "\n" + SelRad);
});
});
你想把它的价值保存到哪里? – Matt
'selected'不是一个收音机将会拥有的属性,但'checked'是。你可以使用'.is'和伪选择器':checked' – SpaceBison