I have this code which is working beautifully. It is just disabling a submit button if text input fields are empty.
$(document).ready(function() {
$('input[required]').on('keyup', function() {
var empty = false;
$('input[required]').each(function() {
var val = $(this).val().trim();
if (val.length == 0 || typeof val == 'undefined') {
empty = true;
}
})
if (empty) {
$('#register').css('opacity', '0.2').attr('disabled', 'disabled');
} else {
$('#register').css('opacity', '1').removeAttr('disabled');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" required>
<input type="text" required>
<button type="button" id="register">register</button>
However, I also have multiple checkbox groups on the page. They have different group names.
How can I also include a check in this code to check that all groups of checkboxes have at least 2 checkboxes selected?
2
Answers
You could use plain JS
this.checked
to check if the checkbox is checked and a simple counter:Then you could instead of checking
if (empty) {...}
, checkif (checked < 2) {...}
.Working example:
If you also want to check this for multiple groups, you could first get all group names with an additional
each()
loop:, filter out the duplicates:
and then iterate over that group names, do the check like in the example above and count the checked groups:
At the end you wouldn’t check for the
true
var, but for:Working example:
Since you are using jQuery you can leverage that – could also use plain JavaScript.
Here is a slight mix of both. I leverage data attributes both in the code and in the CSS to manage the "2" – but this could also be altered to use true checkboxes, radio buttons etc. You mentioned checkboxes but all your inputs are text so I went with your code vs descriptions.
Lots of comments in the code that can and should be removed for a final version.