如何设置无线电选项检查onload与jQuery?
需要检查是否没有设置默认值,然后设置默认值
如何设置无线电选项检查onload与jQuery?
需要检查是否没有设置默认值,然后设置默认值
当前回答
当获取无线电输入值时,请注意以下行为:
$('input[name="myRadio"]').change(function(e) { // Select the radio input group
// This returns the value of the checked radio button
// which triggered the event.
console.log( $(this).val() );
// but this will return the first radio button's value,
// regardless of checked state of the radio group.
console.log( $('input[name="myRadio"]').val() );
});
因此$('input[name="myRadio"]').val()不返回单选输入的检查值,正如您所期望的那样——它返回第一个单选按钮的值。
其他回答
原生JS解决方案:
document.querySelector('input[name=gender][value=Female]').checked = true;
http://jsfiddle.net/jzQvH/75/
HTML:
<input type='radio' name='gender' value='Male'> Male
<input type='radio' name='gender' value='Female'>Female
我喜欢@Amc的答案。我发现表达式可以进一步压缩,以不使用filter()调用(@chaiko显然也注意到了这一点)。同样,对于jQuery v1.6+, prop()是对抗attr()的方法,请参阅jQuery文档中关于prop()的官方最佳实践。
考虑一下@Paolo Bergantino回答中的相同输入标签。
<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>
更新后的一行代码可能是这样的:
$('input:radio[name="gender"][value="Male"]').prop('checked', true);
如果你想从你的模型中传递一个值,并且想要根据值从加载组中选择一个单选按钮,那么使用:
Jquery:
var priority = Model.Priority; //coming for razor model in this case
var allInputIds = "#slider-vertical-" + itemIndex + " fieldset input";
$(allInputIds).val([priority]); //Select at start up
和html:
<div id="@("slider-vertical-"+Model.Id)">
<fieldset data-role="controlgroup" data-type="horizontal" data-mini="true">
<input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("high-"+Model.Id)" value="1" checked="checked">
<label for="@("high-"+Model.Id)" style="width:100px">@UIStrings.PriorityHighText</label>
<input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("medium-"+Model.Id)" value="2">
<label for="@("medium-"+Model.Id)" style="width:100px">@UIStrings.PriorityMediumText</label>
<input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("low-"+Model.Id)" value="3">
<label for="@("low-"+Model.Id)" style="width:100px">@UIStrings.PriorityLowText</label>
</fieldset>
</div>
我想你可以假设,这个名称是唯一的,组中的所有电台都有相同的名称。然后你可以像这样使用jQuery支持:
$("[name=gender]").val(["Male"]);
注意:传递数组很重要。
的版本:
if (!$("[name=gender]:checked").length) {
$("[name=gender]").val(["Male"]);
}
这将导致form.reset()失败:
$('input:radio[name=gender][value=Male]').attr('checked', true);
但这条可行:
$('input:radio[name=gender][value=Male]').click();