5 11 Votes

jQuery: Disable Submit Button if no Checkbox is selected

Tutorial by Computer Expert | 18/03/2014 at 19:54

Sometimes, we would like to allow submitting a form only if one or at least one check box is checked. In this tip, I would like to show you how to do this using jQuery. The following script is making sure that the submit button is only active or enabled when at least one checkbox is selected.

HTML

Our HTML is a simple form containing three checkboxes and one submit button:

<form action="">
   <input class="cbox" type="checkbox" name="cb1" value="1"> 1
   <input class="cbox" type="checkbox" name="cb2" value="2"> 2
   <input class="cbox" type="checkbox" name="cb3" value="3"> 3
   <input id="bt_submit" type="submit" value="Send">
</form>

JavaScript/jQuery

We let our jQuery code execute after loading the document ($(document).ready).

<script type="text/javascript">

$(document).ready(function() { 

   $('#bt_submit').attr("disabled",true);

   $('.cbox').change(function() {
      $('#bt_submit').attr('disabled', $('.cbox:checked').length == 0);
   });

});

</script>

First of all, we set our submit button to disabled. After that, we apply a function to the checkboxes that is called whenever a checkbox is changed. This function is adjusting the state of the submit botton depending on the selection state.

Attention: This function is only working when JavaScript is activated in the browser of the user. It is no replacement of a check of the user input at server-side.

ReplyPositiveNegativeDateVotes

Axuter

Show Profile | Message
Avatar
810 Votes

And if you only have one checkbox, it is even much more easier to implement:

$("#cbox").click(function() {
   $("#bt_submit").attr("disabled", !this.checked);
});

In this.checked it is stored, whether the clicked checkbox is selected or not. Using !this.checked we can set our submit button to exactly the opposite.
18/03/2014 at 22:04

ReplyPositive Negative
11 Vote

Thanks for this instruction of checkboxes.
16/05/2018 at 07:02

ReplyPositive Negative
11 Vote

Thank you so much ! I'm facing a bit of a problem because it doesn't work when I switch to another page on the table although they have the same id as those on the first page.
14/02/2019 at 16:23

ReplyPositive Negative
Reply

About the Author

Avatar AuthorThe author has not added a short description to his profile yet.
Show Profile | Message

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.