How to check a radio button with jQuery?

前端 未结 30 2084
独厮守ぢ
独厮守ぢ 2020-11-22 08:12

I try to check a radio button with jQuery. Here\'s my code:

相关标签:
30条回答
  • 2020-11-22 08:58
    $("#radio_1").attr('checked', true);
    //or
    $("#radio_1").attr('checked', 'checked');
    
    0 讨论(0)
  • 2020-11-22 09:01

    Surprisingly, the most popular and accepted answer ignores triggering appropriate event despite of the comments. Make sure you invoke .change(), otherwise all the "on change" bindings will ignore this event.

    $("#radio_1").prop("checked", true).change();
    
    0 讨论(0)
  • 2020-11-22 09:01

    Get value:

    $("[name='type'][checked]").attr("value");
    

    Set value:

    $(this).attr({"checked":true}).prop({"checked":true});
    

    Radio Button click add attr checked:

    $("[name='type']").click(function(){
      $("[name='type']").removeAttr("checked");
      $(this).attr({"checked":true}).prop({"checked":true});
    });
    
    0 讨论(0)
  • 2020-11-22 09:01

    attr accepts two strings.

    The correct way is:

    jQuery("#radio_1").attr('checked', 'true');
    
    0 讨论(0)
  • 2020-11-22 09:03

    Short and easy to read option:

    $("#radio_1").is(":checked")
    

    It returns true or false, so you can use it in "if" statement.

    0 讨论(0)
  • 2020-11-22 09:03

    Use prop() mehtod

    Source Link

    <p>
        <h5>Radio Selection</h5>
    
        <label>
            <input type="radio" name="myRadio" value="1"> Option 1
        </label>
        <label>
            <input type="radio" name="myRadio" value="2"> Option 2
        </label>
        <label>
            <input type="radio" name="myRadio" value="3"> Option 3
        </label>
    </p>
    
    <p>
        <button>Check Radio Option 2</button>
    </p>
    
    
    <script>
        $(function () {
    
            $("button").click(function () {
                $("input:radio[value='2']").prop('checked',true);
            });
    
        });
    </script>
    
    0 讨论(0)
提交回复
热议问题