how to set radio option checked onload with jQuery

后端 未结 16 2086
陌清茗
陌清茗 2020-12-04 04:42

How to set radio option checked onload with jQuery?

Need to check if no default is set and then set a default

相关标签:
16条回答
  • 2020-12-04 05:22

    This one will cause form.reset() failure:

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

    But this one works:

    $('input:radio[name=gender][value=Male]').click();
    
    0 讨论(0)
  • 2020-12-04 05:22

    Native JS solution:

     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
    
    0 讨论(0)
  • 2020-12-04 05:32

    I think you can assume, that name is unique and all radio in group has the same name. Then you can use jQuery support like that:

    $("[name=gender]").val(["Male"]);
    

    Note: Passing array is important.

    Conditioned version:

    if (!$("[name=gender]:checked").length) {
        $("[name=gender]").val(["Male"]);
    }
    
    0 讨论(0)
  • 2020-12-04 05:33

    Note this behavior when getting radio input values:

    $('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() ); 
    
    });
    

    So $('input[name="myRadio"]').val() does not return the checked value of the radio input, as you might expect -- it returns the first radio button's value.

    0 讨论(0)
提交回复
热议问题