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

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


当前回答

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

其他回答

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

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

但这条可行:

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

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

<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');

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

$('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 type='radio' name='gender' value='Male'>
    <input type='radio' name='gender' value='Female'>

你想检查一个值为“Male”的onload,如果没有检查无线电:

    $(function() {
        var $radios = $('input:radio[name=gender]');
        if($radios.is(':checked') === false) {
            $radios.filter('[value=Male]').prop('checked', true);
        }
    });