How to uncheck a checkbox in pure JavaScript?

后端 未结 4 1988
萌比男神i
萌比男神i 2020-12-10 00:40

Here is the HTML Code:

4条回答
  •  我在风中等你
    2020-12-10 00:56

    Recommended, without jQuery:

    Give your an ID and refer to that. Also, remove the checked="" part of the tag if you want the checkbox to start out unticked. Then it's:

    document.getElementById("my-checkbox").checked = true;
    

    Pure JavaScript, with no Element ID (#1):

    var inputs = document.getElementsByTagName('input');
    
    for(var i = 0; i

    Pure Javascript, with no Element ID (#2):

    document.querySelectorAll('.text input[name="copyNewAddrToBilling"]')[0].checked = true;
    
    document.querySelector('.text input[name="copyNewAddrToBilling"]').checked = true;
    

    Note that the querySelectorAll and querySelector methods are supported in these browsers: IE8+, Chrome 4+, Safari 3.1+, Firefox 3.5+ and all mobile browsers.

    If the element may be missing, you should test for its existence, e.g.:

    var input = document.querySelector('.text input[name="copyNewAddrToBilling"]');
    if (!input) { return; }
    

    With jQuery:

    $('.text input[name="copyNewAddrToBilling"]').prop('checked', true);
    

提交回复
热议问题