how to set radio option checked onload with jQuery

后端 未结 16 2085
陌清茗
陌清茗 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:16

    How about a one liner?

    $('input:radio[name="gender"]').filter('[value="Male"]').attr('checked', true);
    
    0 讨论(0)
  • 2020-12-04 05:16
     $("form input:[name=gender]").filter('[value=Male]').attr('checked', true);
    
    0 讨论(0)
  • 2020-12-04 05:18

    //If you are doing it on javascript or a framework like backbone, you will encounter this a lot you could have something like this

    $MobileRadio = $( '#mobileUrlRadio' );
    

    while

    $MobileRadio.checked = true;
    

    will not work,

    $MobileRadio[0].checked = true;
    

    will.

    your selector can be as the other guys above recommended too.

    0 讨论(0)
  • 2020-12-04 05:21

    Say you had radio buttons like these, for example:

    <input type='radio' name='gender' value='Male'>
    <input type='radio' name='gender' value='Female'>
    

    And you wanted to check the one with a value of "Male" onload if no radio is checked:

    $(function() {
        var $radios = $('input:radio[name=gender]');
        if($radios.is(':checked') === false) {
            $radios.filter('[value=Male]').prop('checked', true);
        }
    });
    
    0 讨论(0)
  • 2020-12-04 05:21

    If you want it to be truly dynamic and select the radio that corresponds to the incoming data, this works. It's using the gender value of the data passed in or uses default.

    if(data['gender'] == ''){
     $('input:radio[name="gender"][value="Male"]').prop('checked', true);
    }else{
      $('input:radio[name="gender"][value="' + data['gender'] +'"]').prop('checked', true);
    };
    
    0 讨论(0)
  • 2020-12-04 05:21

    Here is example with above methods:

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

    In javascript:

    $("[name = 'radio-choice-2'][value='choice3']").prop('checked', true).checkboxradio('refresh');
    
    0 讨论(0)
提交回复
热议问题