Eamonn Eamonn - 1 year ago 36
Javascript Question

JQuery: Checkbox as radiobutton, without default selection

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')) {
$(this).attr('checked', true);

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

Answer Source
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