I have a simple form with some checkboxes and I’m trying to get it so that the submit button is enabled when all the checkboxes are checked.
I’ve been messing with some of the answers from here: Enable submit button only when all fields are filled
But it seems like it either doesn’t enable the submit button or it enables it right after one is checked. Here’s what I have:
$(document).on("change keyup", ".required", function(e) {
let Disabled = true;
$(".required").each(function() {
let value = this.value;
if (value && value.trim() != "") {
Disabled = false;
} else {
Disabled = true;
return false;
}
});
if (Disabled) {
$(".toggle-disabled").prop("disabled", true);
} else {
$(".toggle-disabled").prop("disabled", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#">
<p>
<label>
<input type="checkbox" class="filled-in box required" name="item" />
<span>Filled in</span>
</label>
</p>
<p>
<label>
<input type="checkbox" class="filled-in box required" name="item" />
<span>Filled in</span>
</label>
</p>
<p>
<label>
<input type="checkbox" class="filled-in box required" name="item" />
<span>Filled in</span>
</label>
</p>
<p>
<button type="button" class="toggle-disabled" disabled>Submit</button>
</p>
</form>
It’s weird cause it sorta works, but as soon as I check one box the submit button is enabled. Looks like I have all the pieces there, but not sure if it’s something within the change keyup
or something else.
6
Answers
EventListener
to check for changes made within the input (checkboxes). You do not need to listen to all changes orkeyups
on the entire document. So just use$('form input[type="checkbox"]').change(function(){ ... }
which going to save resources.$('form input[type="checkbox"]:not(:checked)').length
. This will give the exact number of checkboxes that are currently unchecked.if/else-statement
to see if that count is higher than 0 (which means that at least 1 checkbox is still unchecked. In my example I replaced theif/else-statement
with aconditional ternary operator
to save a few lines:You have to keep track of count as suggested by @tacoshy, I have modified your code to reflect the changes.
Assuming that it is just checkboxes and not other inputs you can just check the length of checked vs all checkboxes.
Doing it with array some
Just compare checked and not checked counts on any change.
input[type="submit"]
alsoAlternative
try this: