0

Here's my example: http://hamzakhan.name/dev/eric/options/five/fiveage.html

As you can see, there are two checkboxes in each box. I tried adding this javascript from make checkbox behave like radio buttons with javascript by adding this script under the html form code:

<script>
$(".agecb").each(function()
{
    $(this).change(function()
    {
        $(".agecb").prop('checked',false);
        $(this).prop('checked',true);
    });
});
</script>

but it's not working. As you see, when I try to click on one checkbox and then click on another checkbox in the next panel, the first one unchecked. How do I fix that? I want it to work across each panel.

Community
  • 1
  • 1
Kristina Bressler
  • 1,642
  • 1
  • 25
  • 60
  • Please post your example HTML here, not on a live website. – Barmar May 12 '15 at 02:36
  • Why don't you just use radio buttons, instead of making checkboxes that act like radio buttons. – Barmar May 12 '15 at 02:37
  • I did check out many methods on both checkboxes and radio buttons and finally settled on that code that make the checkboxes act like radio buttons . It seems like best method for what I was looking for. Also thanks to PeterKA for his help! – Kristina Bressler May 12 '15 at 03:03

3 Answers3

3

You need to uncheck only the other checkboxes in the same form, not all the checkboxes. You also don't need to use .each(), jQuery does that automatically when you call an event binding function (and most other functions that make sense to operate on all elements in a collection).

$(".agecb").change(function() {
    $(this).closest(".ageform").find(".agecb").prop('checked', false);
    $(this).prop('checked', true);
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Bear in mind that there is context; in your case each pair of checkboxes is within a form element:

$('.agecb').on('change', function() {
    this.checked = true;
    $(this).closest('form').find('.agecb').not(this).prop('checked', false);
});

Demo

PeterKA
  • 24,158
  • 5
  • 26
  • 48
0

If you want to make a "one group checkbox", give them the same name as describe in the documentation http://www.w3schools.com/tags/att_input_checked.asp

<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>

But, if you want to make only one item selected in each "group", you better use radio button.

destraaaa
  • 96
  • 5