Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check box attributes checked is true, but tick is not shown

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:

like image 739
gotqn Avatar asked Jul 05 '13 21:07

gotqn


People also ask

How do you check if checkbox is ticked or not?

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.

Does checkbox return true or false?

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.

Does checkbox have value attribute?

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.

What is checkbox value if not checked?

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.


1 Answers

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.

like image 152
dsgriffin Avatar answered Oct 31 '22 05:10

dsgriffin