且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用javascript检查单选按钮

更新时间:2023-11-29 09:24:52


  • 为什么使用 all 而不是 id


  • 也不要将CSS语法()用于原生JS

    b $ b

    Native JS解决方案



    document.getElementById(_ 1234)。checked = true;



    JQuery解决方案: b
    $ b

    $(#_ 1234)。prop(checked,true);


    For some reason, I can't seem to figure this out.

    I have some radio buttons in my html which toggles categories:

    <input type="radio" name="main-categories" id="_1234" value="1234" /> // All
    <input type="radio" name="main-categories" id="_2345" value="2345" /> // Certain category
    <input type="radio" name="main-categories" id="_3456" value="3456" /> // Certain category
    <input type="radio" name="main-categories" id="_4567" value="4567" /> // Certain category
    

    The user can select whichever he/she wants, but when an certain event triggers, I want to set 1234 to be set checked radio button, because this is the default checked radio button.

    I have tried versions of this (with and without jQuery):

    document.getElementById('#_1234').checked = true;

    But it doesn't seem to update. I need it to visibly update so the user can see it. Can anybody help?

    EDIT: I'm just tired and overlooked the #, thanks for pointing it out, that and $.prop().

    1. Why do you use all instead of id value?

    2. Also do not mix CSS syntax (# for identifier) with native JS

    Native JS solution:

    document.getElementById("_1234").checked = true;

    JQuery solution:

    $("#_1234").prop("checked", true);