I have the following jQuery code to make my checkboxes act like radio buttons, so that only 1 of the 3 can be checked at a time.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#testing input:checkbox").change(function(){
var checkname = $(this).attr("name");
$("input:checkbox[name='" + checkname + "']").removeAttr("checked");
this.checked = true;
});
});
</script>
The checkboxes are layed out like the following:
<input type="checkbox" id="testing" name="testing" value="B">
<input type="checkbox" id="testing" name="testing" value="I">
<input type="checkbox" id="testing" name="testing" value="A">
This works exactly how i want it to work, not a problem, except once i click one of the 3, i cant unclick it so that none of them are checked, this is what i want to happen, so along with being only able to click one at a time, im able to uncheck them completely.
Any help would be grand :)
To make checkbox behave like radio buttons with JavaScript, we can listen to the body element's click listener. And in the listener, we uncheck all the checkboxes and the check off the one that matches the one that's clicked.
Answer: Use the jQuery prop() method You can use the jQuery prop() method to check or uncheck a checkbox dynamically such as on click of button or an hyperlink etc. The prop() method require jQuery 1.6 and above.
Checkboxes and radio buttons are elements for making selections. Checkboxes allow the user to choose items from a fixed number of alternatives, while radio buttons allow the user to choose exactly one item from a list of several predefined alternatives.
Only run the code that unchecks the others if this
has been checked
.
Example: http://jsfiddle.net/CX5Th/1/
$("#testing input:checkbox").change(function() {
if( this.checked ) {
var checkname = $(this).attr("name");
$("input:checkbox[name='" + checkname + "']").removeAttr("checked");
this.checked = true;
}
});
EDIT: Here's a revision that prevents the newly checked box from being unchecked when you select the boxes with the same name. It uses not()
(docs) to exclude the current checkbox.
Example: http://jsfiddle.net/CX5Th/2/
$("#testing input:checkbox").change(function() {
if (this.checked) {
var checkname = $(this).attr("name");
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
}
});
Less Code! :-)
var boxes = $("input:checkbox").click(function(){
boxes.not(this).attr('checked', false);
});
http://jsfiddle.net/YqSXA/1/
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