How to clear radio button in Javascript?

后端 未结 10 487
予麋鹿
予麋鹿 2020-12-02 19:57

I have a radio button named \"Choose\" with the options yes and no. If I select any one of the options and click the button labeled \"clear\", I need to clear the selected o

相关标签:
10条回答
  • 2020-12-02 20:11

    Simple, no jQuery required:

    <a href="javascript:clearChecks('group1')">clear</a>
    
    <script type="text/javascript">
    function clearChecks(radioName) {
        var radio = document.form1[radioName]
        for(x=0;x<radio.length;x++) {
            document.form1[radioName][x].checked = false
        }
    }
    
    </script>
    
    0 讨论(0)
  • 2020-12-02 20:16
    YES<input type="radio" name="group1" id="sal" value="YES" >
    
    NO<input type="radio" name="group1" id="sal1" value="NO" >
    
    <input type="button" onclick="document.getElementById('sal').checked=false;document.getElementById('sal1').checked=false">
    
    0 讨论(0)
  • 2020-12-02 20:21

    This should work. Make sure each button has a unique ID. (Replace Choose_Yes and Choose_No with the IDs of your two radio buttons)

    document.getElementById("Choose_Yes").checked = false;
    document.getElementById("Choose_No").checked = false;
    

    An example of how the radio buttons should be named:

    <input type="radio" name="Choose" id="Choose_Yes" value="1" /> Yes
    <input type="radio" name="Choose" id="Choose_No" value="2" /> No
    
    0 讨论(0)
  • 2020-12-02 20:23

    You don't need to have unique id for the elements, you can access them by their name attribute:

    If you're using name="Choose", then:

    • With jQuery it is as simple as:

      $('input[name=Choose]').attr('checked',false);
      
    • or in pure JavaScript:

         var ele = document.getElementsByName("Choose");
         for(var i=0;i<ele.length;i++)
            ele[i].checked = false;
      

      Demo for JavaScript

    0 讨论(0)
  • 2020-12-02 20:25

    If you do not intend to use jQuery, you can use simple javascript like this

    document.querySelector('input[name="Choose"]:checked').checked = false;
    

    Only benefit with this is you don't have to use loops for two radio buttons

    0 讨论(0)
  • 2020-12-02 20:28

    An ES6 approach to clearing a group of radio buttons:

        Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
    
    0 讨论(0)
提交回复
热议问题