Reputation: 19
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label><br>
let's say we have this code can i disallow the user to choose bike and boat together using javascript or anything else
i have tried this javascript code to limit the choices
$(document).ready(function () { $("input[name='value3']").change(function () { var maxAllowed = 2; var cnt = $("input[name='value3']:checked").length; if (cnt > maxAllowed) { $(this).prop("checked", ""); alert('You can select maximum ' + maxAllowed + ' options!!'); } }); });
but i still need to limitate the choices more and prevent choosing a specific option along with a specific one
Upvotes: 1
Views: 81
Reputation: 31992
You can unselect all other checkboxes when the user selects a checkbox by listening for the change
event:
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(e => e.addEventListener('change', () => checkboxes.forEach(f => f != e ? f.checked = false : '')))
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label><br>
However, the better choice is to make the inputs radio buttons instead of checkboxes.
<input type="radio" id="vehicle1" name="vehicle" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="radio" id="vehicle2" name="vehicle" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="radio" id="vehicle3" name="vehicle" value="Boat">
<label for="vehicle3"> I have a boat</label><br>
Upvotes: 2