12

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:

Sam
  • 7,252
  • 16
  • 46
  • 65
gotqn
  • 42,737
  • 46
  • 157
  • 243

2 Answers2

26

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.

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
6

You can try it this way :

$('input[name=checkBoxName]').parents('span').addClass("checked");
$("input[name=checkBoxName]").prop('checked', 'checked');

The first line is to display the tick in the check box and the second line is to actually check it.

  • 1
    Is this related to a UI library, like bootstrap? I just spent a lot of time and this solved the issue. But to my knowledge just setting with `prop(...)` should work too (the checkbox is not always packed into a `span`), so I have no idea why this worked in my case. – tokosh Jun 30 '16 at 03:40
  • This is to check the box using JQuery. – Lalit Narayan Mishra Jan 22 '19 at 04:24
  • Only the second line is generic enough to use on other people cases. – Abdillah Aug 25 '19 at 15:00