Home /Jquery /Button should be enabled if at least one checkbox is checked

Button should be enabled if at least one checkbox is checked

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.

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

<form>

<div>

<input type=”checkbox” name=”option-1″ id=”option-1″> <label for=”option-1″>Option 1</label></div>

<div>

<input type=”checkbox” name=”option-2″ id=”option-2″> <label for=”option-2″>Option 2</label>

</div>

<div>

<input type=”checkbox” name=”option-3″ id=”option-3″> <label for=”option-3″>Option 3</label>

</div>

<div>

<input type=”checkbox” name=”option-4″ id=”option-4″> <label for=”option-4″>Option 4</label>

</div>

<div>

<input type=”checkbox” name=”option-5″ id=”option-5″> <label for=”option-5″>Option 5</label>

</div><div>

<input type=”submit” value=”Do thing” disabled>

</div>

</form>

 

JavaScript/jQuery

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

<script type=”text/javascript”>

$(document).ready(function() {

var checkboxes = $(“input[type=’checkbox’]”),

submitButt = $(“input[type=’submit’]”);

checkboxes.click(function() {

submitButt.attr(“disabled”, !checkboxes.is(“:checked”));

});

});

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.

Leave a Reply