I want to validate for maximum checked by user to 3. If user check more than 3, i want to show to user maximum available is 3 OR I want to disable others checkbox before submit form with javascript or jquery
<div class="seatplan">
<input type='checkbox' name='A1' value='200'>
<input type='checkbox' name='A2' value='200'>
<input type='checkbox' name='A3' value='300'>
<input type='checkbox' name='A4' value='200'>
<input type='checkbox' name='A5' value='300'>
</div>
Please check out the below code. Hope it helps:
$('.seatplan input[type=checkbox]').change(function() {
var checked = $('.seatplan input[type=checkbox]:checked').length;
console.log(checked);
if (checked >= 3) {
$('.seatplan input[type=checkbox]').not(':checked').prop('disabled', true);
} else {
$('.seatplan input[type=checkbox]').prop('disabled', false);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="seatplan">
<input type='checkbox' name='A1' value='200'>
<input type='checkbox' name='A2' value='200'>
<input type='checkbox' name='A3' value='300'>
<input type='checkbox' name='A4' value='200'>
<input type='checkbox' name='A5' value='300'>
</div>
Basically I'm listening to the change event of each checkbox and then based on the length of the checked items, I disable/enable the rest of the checkboxes.
If you want to go without jQuery you could do:
const seatplan = document.querySelector('.seatplan');
seatplan.addEventListener('change', (e) => {
const checked = seatplan.querySelectorAll('input:checked');
const unchecked = seatplan.querySelectorAll('input:not(:checked)');
if (checked.length >= 3) {
unchecked.forEach(el => el.setAttribute('disabled', true));
} else {
unchecked.forEach(el => el.removeAttribute('disabled'));
}
});
.seatplan > input{
height: 2em;
width: 2em;
cursor: pointer;
}
.seatplan > input:disabled{
cursor: not-allowed;
}
<div class="seatplan">
<input type='checkbox' name='A1' value='200'>
<input type='checkbox' name='A2' value='200'>
<input type='checkbox' name='A3' value='300'>
<input type='checkbox' name='A4' value='200'>
<input type='checkbox' name='A5' value='300'>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With