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

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


当前回答

下面是使用上述方法的示例:

<div class="ui-field-contain">
<fieldset data-role="controlgroup" data-type="horizontal">    <legend>Choose a pet:</legend>
    <input type="radio" name="radio-choice-2" id="radio-choice-1" value="choice1">
    <label for="radio-choice-1">Cat</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-2" value="choice2">
    <label for="radio-choice-2">Dog</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-3" value="choice3">
    <label for="radio-choice-3">Hamster</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-4" value="choice4">
    <label for="radio-choice-4">Lizard</label>
  </fieldset>
</div>

在javascript中:

$("[name = 'radio-choice-2'][value='choice3']").prop('checked', true).checkboxradio('refresh');

其他回答

不需要这些。 使用简单而古老的HTML,您可以实现您想要的。 如果你让你想检查的收音机默认是这样的: <input type='radio' name='gender' checked='true' value='Male'> 当页面加载,它会来检查。

单程怎么样?

$('input:radio[name="gender"]').filter('[value="Male"]').attr('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

这将导致form.reset()失败:

$('input:radio[name=gender][value=Male]').attr('checked', true);

但这条可行:

$('input:radio[name=gender][value=Male]').click();