[ACCEPTED]-How can I prevent a user from selecting multiple checkboxes in HTML?-checkbox
you should change it to radio button instead 1 of check box!
<input type="radio" name="group1" id="item1" value="Milk">
<label for="item1">Milk</label>
<br/>
<input type="radio" name="group1" id="item2" value="Butter" checked>
<label for="item2">Butter</label>
<br/>
<input type="radio" name="group1" id="item3" value="Cheese">
<label for="item13">Cheese</label>
I had a use case where I needed use checkboxes--which, unlike 7 radio buttons, allows a user to UNcheck... Here's 6 an example of something I pieced together 5 from another stackoverflow user:
<head>
<meta charset=utf-8 />
<title>and-or checkboxes</title>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<label for="checkbox1"><input type="checkbox" id="checkbox1" name="checkbox1" value="and" </label><span id="span_and">checkbox1</span><br>
<label for="checkbox2"> <input type="checkbox" id="checkbox2" name="checkbox2" value="or" </label><span id="span_or">checkbox2</span>
<script>
$(document).ready(function(){
$('#checkbox1').click(function() {
var checkedBox = $(this).attr("checked");
if (checkedBox === true) {
$("#checkbox2").attr('checked', false);
} else {
$("#checkbox2").removeAttr('checked');
}
});
});
$(document).ready(function(){
$('#checkbox2').click(function() {
var checkedBox = $(this).attr("checked");
if (checkedBox === true) {
$("#checkbox1").attr('checked', false);
} else {
$("#checkbox1").removeAttr('checked');
}
});
});
</script>
</body>
With a 4 little work, you can combine the either/or 3 two scripts into a single script. You probably 2 don't need this now but I wanted to post 1 it because it was very useful to me.
If you want that only one checkbox get selected 1 at a time then its better to use radiobutton
instead.
If you mean that you don't want multiple 4 checkboxes from a same "logical group" to 3 be checked at one time, you should use radio 2 buttons instead of checkboxes.
<form>
<input type="radio" name="aGroup" value="choice1" /> Choice #1<br />
<input type="radio" name="aGroup" value="choice2" /> Choice #2
</form>
By using this, only 1 1 option can be checked at one time
Use Radio, and they must have the same name=""
.
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.