I have two check boxes, that I want to make to behave like they are radio buttons (only one of them is checked at time).
So, I have easy found a jQuery solution that should do the trick:
$("input:checkbox").click(function(){
var group = "input:checkbox[name='"+$(this).attr("name")+"']";
$(group).attr("checked",false);
$(this).attr("checked",true);
});
The HTML looks like this:
<div class="radio">
<label for="q_is_active_true">Is active</label>
<input name="radio_buttons" type="hidden" value="0"><input id="q_is_active_true" name="radio_buttons" type="checkbox" value="1">
<label for="q_is_active_false">Is not active</label>
<input name="radio_buttons" type="hidden" value="0"><input id="q_is_active_false" name="radio_buttons" type="checkbox" value="1">
</div>
But when I click on one of the check boxes, even its "check" attribute is set to "checked" no tick is shown:
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.
Note: Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently checked . If it is, then the value of the checkbox's value attribute is reported as the input's value.
If a checkbox is unchecked, it doesn't get sent, so setting it's value to 0 if it isn't checked isn't going to help - it will always return NULL.
You need to be setting the checked status by it's property to achieve what you want:
$("input:checkbox").click(function(){
var group = "input:checkbox[name='"+$(this).attr("name")+"']";
$(group).prop("checked", false);
$(this).prop("checked", true);
});
jsFiddle here.
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