Skip to content
Related Articles

Related Articles

Improve Article
How to uncheck all other checkboxes apart from one using jQuery ?
  • Last Updated : 14 Apr, 2021

In this article, we will see how to uncheck all checkboxes except first using jQuery.

Approach: First, we need to get all check box elements in a page. We can get all the check-boxes using the following jQuery call:

$('input[type=checkbox]')

Next we can use jQuery each function to iterate over each checkbox,

each(function (index, checkbox){
     if (index != 0) {
     checkbox.checked = false;
    }
 });

In the above snippet, we pass a function to each method. That function uses two parameters, index and current element reference. In this function, we check index of each checkbox. If index is 0, we do nothing. If index is not zero,  we uncheck the current checkbox element. 

 



Example: Below is the code that illustrates the use of above approach.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script type="text/javascript" src=
    </script>
  
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnUncheckAll').click(function () {
                $('input[type=checkbox]').each(
                  function (index, checkbox) {
                    if (index != 0) {
                        checkbox.checked = false;
                    }
                });
            });
        });
    </script>
</head>
  
<body style="text-align:center">
    <label for="cb1">CheckBox 1</label>
    <input type="checkbox" value="cb1"/>
    <br/>
  
    <label for="cb2">CheckBox 2</label>
    <input type="checkbox" value="cb2"/>
    <br/>
  
    <label for="cb3">CheckBox 3</label>
    <input type="checkbox" value="cb3"/>
    <br/>
  
    <label for="cb4">CheckBox 4</label>
    <input type="checkbox" value="cb4"/>
    <br/>
  
    <label for="cb5">CheckBox 5</label>
    <input type="checkbox" value="cb5"/>
    <br/>
  
    <br/>
    <input type="button" 
           value="Uncheck all checkboxes but first" 
           id="btnUncheckAll"/>
</body>
  
</html>

Output: We see the following web page:

Now check all the checkboxes.

After clicking on button: All the checkboxes gets unchecked except the first one.




My Personal Notes arrow_drop_up
Recommended Articles
Page :