JS - Function: Add Checkboxes to table that act like radio buttons

Hi

This is an adapted function from here JavaScript & jQuery Examples. It will add checkboxes to the rows then make them work like radio buttons so that only one row can be selected.

function addRadioTypeChecksToTable(view) {
    $('#' + view.key + '.kn-table thead tr').prepend('<th></th>');
    // Add a checkbox to each row in the table body
    $('#' + view.key + '.kn-table tbody tr').each(function() {
      $(this).prepend('<td><input type="checkbox"></td>').css('max-width', '32px');
    });
    //Add Listener to Checkboexes which unchecks all other checkboxes
    $("#" + view.key + " input[type=checkbox]").click(function () {
      $("input[type=checkbox]").prop('checked',false);
        $(this).prop('checked',true);
    });
    
}

Just call the function from the view render that has your table

Craig

2 Likes

Awesome @CSWinnall this simplifies a very old function I’d used.

We can add actual radio buttons if we want by setting the input type to radio, e.g.:
$(this).prepend('<td><input type="radio"></td>').css('max-width', '32px');

The .prop('checked') setting also works for radios.

1 Like

@BradStevens
I actually didn’t think of that. Doh!

Craig