如何设置无线电选项检查onload与jQuery?

需要检查是否没有设置默认值,然后设置默认值


当前回答

//如果你在javascript或者像backbone这样的框架上做,你会遇到很多这种情况 可以是这样的

$MobileRadio = $( '#mobileUrlRadio' );

$MobileRadio.checked = true;

不会起作用,

$MobileRadio[0].checked = true;

会的。

你的选择器也可以像上面推荐的那样。

其他回答

当获取无线电输入值时,请注意以下行为:

$('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()不返回单选输入的检查值,正如您所期望的那样——它返回第一个单选按钮的值。

这适用于多个单选按钮

$('input:radio[name="Aspirant.Gender"][value='+jsonData.Gender+']').prop('checked', true);

原生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

JQuery实际上有两种方法来设置复选框和复选框的复选状态,这取决于你是否在HTML标记中使用value属性:

如果他们有价值属性:

$("[name=myRadio]").val(["myValue"]);

如果它们没有value属性:

$("#myRadio1").prop("checked", true);

更多的细节

在第一种情况下,我们使用名称指定整个无线电组,并告诉JQuery使用val函数找到要选择的无线电。val函数接受一个元素数组,并找到匹配值的无线电,设置其checked=true。其他同名的人将被罢免。如果没有找到匹配值的无线电,那么将取消所有的选择。如果有多个具有相同名称和值的无线电,则最后一个将被选中,其他将被取消选中。

如果您没有为radio使用value属性,那么您需要使用唯一ID来选择组中的特定radio。在这种情况下,您需要使用prop函数设置“checked”属性。许多人不使用值属性复选框,所以#2更适用于复选框,而不是无线电。还要注意,当复选框具有相同的名称时,它们不会形成组,您可以执行$("[name=myCheckBox")。道具(“检查”,真正的);复选框。

您可以在这里使用此代码:http://jsbin.com/OSULAtu/1/edit?html,output

如果你想从你的模型中传递一个值,并且想要根据值从加载组中选择一个单选按钮,那么使用:

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>