0

I have a dynamically generated list, of random length from zero items up, where each item includes by a checkbox. Unlike radio buttons, all of the checkboxes can be unchecked, but like radio buttons only one can be checked. To enforce this, I am using JQuery (based on the answer given here: jQuery - checkboxes like radiobuttons)

My code as it currently stands is:

var $radiocheck = $('input.radiocheck');
$radiocheck.click(function() {
    if($(this).is(':checked')) {
        $(this).attr('checked', false);
    }
    else if($(this).not(':checked')) {
        $radiocheck.removeAttr('checked');
        $(this).attr('checked', true);
    }
});

...but it doesn't work (checkboxes remain unchecked on click). Any help is appreciated!

Community
  • 1
  • 1
Eamonn
  • 1,338
  • 2
  • 21
  • 53
  • 1
    Add an extra radio button for "none of the above". You run the risk of confusing your users if you cause checkboxes to behave like something else. – Blazemonger May 08 '12 at 18:48

3 Answers3

4
var $radiocheck = $('input.radiocheck');

$radiocheck.on('click', function() {
    $radiocheck.not(this).prop('checked', false);
    this.checked = this.checked===true ? true:false; // to toggle, otherwise just set to true
});​

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    awesome answer, but use `.prop("checked", false);` to replace .attr() call. [.prop()](http://api.jquery.com/prop/) – DefyGravity May 08 '12 at 18:41
1

One:

    var $radiocheck = $('input.radiocheck');

    $radiocheck.on('click', function() {
        $radiocheck.not(this).attr('checked', false);
        this.checked = this.checked;
    });

DEMO: One

Two:

   var $radiocheck = $('input.radiocheck');

   $radiocheck.on('click', function() {
     $radiocheck.not(this).attr('checked', false).find(this).attr('checked', this.checked);
   });

DEMO: Two

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
1

Another answer using adeneo's approach but without using css classes for selection:

$(document).ready(function() {
   var $radiocheck = $(":checkbox");
   $radiocheck.on('click', function() {
     $radiocheck.not(this).attr('checked', false);
     this.checked = this.checked === true ? true : false;
   });
 });

FIDDLE