Set checkbox to "checked" when a row is selected.

Set checkbox to "checked" when a row is selected.

ClarkBClarkB Posts: 8Questions: 3Answers: 0
edited January 2018 in Free community support

My table has a column with checkboxes in it, and I have it working correctly, returning the list of selected row ids to my Rails 5 controller. But I'd prefer to use the Select extension, and hide the checkbox column. I found a way to set the initial selection based on the checkbox state (might be clunky - any tips appreciated):

 table.rows().every( function () {
    if(this.data()[0].includes('checked="checked"')){
      this.select();
    } else {
      this.deselect();
    }
  });

Now, on submit, I want to set the checkbox state for all the rows based on their Select status. Not sure how to do that? I assumed I would just iterate the table again, but I don't see a is_selected() function for a row. And I don't know how to set the checkbox state for an input in a row as I iterate over them. I'm a js noob - more of a backend guy - so please forgive me it the answer is obvious.

Answers

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947

    Not sure I totally understand what you want to do but using the Select extension its easy to get the selected rows. This example shows how:
    https://datatables.net/extensions/select/examples/api/get.html

    Sounds like you don't want to use checkboxes. If thats the case then you should be able to remove that column and still use the Select extension. Unless you need them it seems like extra work to set the check state if they are hidden.

    on submit, I want to set the checkbox state for all the rows based on their Select status

    Not sure what you are doing when you say on submit but you could reselect rows that were previously selected. I was working on something like this yesterday. I have a table that refreshes the data periodically. I wanted to select a row and keep it selected through the process. But since I use clear() the selected row is no longer selected. I put together this example to figure out how to reselect the row(s) after clearing the table:
    http://live.datatables.net/wopidofe/1/edit

    First I get all the selected rows with this:
    var rows = $('#example').DataTable().rows( { selected: true } ).indexes();

    Then clear and add the updated data. Then I use this to reselect the rows:
    $('#example').DataTable().rows(rows).select();

    This works in my case because the key data (names, number of rows, etc) don't change, just counters. Using the rows().indexes() may or may not work depending on what you are trying to do.

    After all that I may be way off base of what you are trying to do :smile:

    Kevin

This discussion has been closed.