Updating checkbox status back to the table

Updating checkbox status back to the table

outage027outage027 Posts: 4Questions: 1Answers: 0

Hello,

New to JS and DataTables and I'm looking for some understanding on how to work with DataTables.

I have successfully loaded a DataTable that has three checkboxes per row where only 0 or 1 checkboxes can be checked per row. Each row also has other data like Name, Category, etc.

The DataTable is populated in an .ejs file from two plist files that were parsed into arrays. I am creating and populating the checkboxes like this:

          <% all_titles.forEach((data, index) => { %>
            <tr>
              <% if (default_action.add.includes(data.name)) { %>
                <td><input type="checkbox" id="checkbox" name="Group<%= index + 1 %>" value="Add" checked></td>
                <% } else { %>
                  <td><input type="checkbox" name="Group<%= index + 1 %>" value="Add"></td>
                <% } %>
              <% if (default_action.remove.includes(data.name)) { %>
                <td><input type="checkbox" id="checkbox" name="Group<%= index + 1 %>" value="Remove" checked></td>
                <% } else { %>
                  <td><input type="checkbox" name="Group<%= index + 1 %>" value="Remove"></td>
                <% } %>
              <td><%= data.category %></td>
              <td class="name"> <%= data.name %></td>
            </tr>
          <% }); %>

If I make changes in the checkboxes I notice the following:

  • If I refresh the page, the checkboxes are remembered and not reloaded from the file. I would like it to reload from the file.
  • If I inspect the page, the html doesn't change, even though the checkboxes do. I would suspect that the 'checked=' would change with a change in checkbox state.
  • If I output the DataTable, I get the original data from the file that populated the table, regardless of the state of the checkboxes, or even if I refresh the page.
// Output DataTable
var form_data  = table.rows().data()
console.log(form_data)

If my goal is to read the current state of the DataTable and rewrite one of the files used to populate it, then:

  • Is it important that the HTML gets updated? (I have code that will do that, but it doesn't change the output of the DataTable.
  • How do I update the checkboxes so that the above command prints out the correct checkbox state per row?
  • Is this even important? Is there a better way to gather the DataTable state, write the file, and then if necessary reload the DataTable from the updated file?

I am aware of the gyrocode plugin, and think I have it set up right. I can't figure out how to get any of the API commands to work, and not sure what I even would want them to do. I suspect I need to update the DataTable when I click or unclick a checkbox so that when I output the data in the DataTable, it matches what I visually see. I can then line by line rebuild an array that I can convert back to a plist file and save it.

Here is my DataTable code.

let table = new DataTable('#search_table', {
    "columns": [
        { "width": "5%" },
        { "width": "5%" },
        null,
        null
    ],
    "columnDefs": [
        {
            'targets': [0, 1],
            'checboxes': true,
        }
    ],
    "order": [
        [2, "asc"],
        [3, "desc"]
    ]
});
    
// Updating html may not be necessary as table is loaded from array derived from plist.
// If you write the plist, then reload from it, the HTML nor Datatable values may not matter.  
// 
$('input[type="checkbox"]').on('change', function() {
   console.log('Is checked? : ', this.checked) //This outputs true or false based on if box is checked. 
   console.log('value by API : ', table.cell({ row: this.parentNode.rowIndex, column : this.cellIndex }).data()); //This outputs what seems like the first checkbox
   $('input[name="' + this.name + '"]').not(this).prop('checked', false); //Prevents checking two checkboxes at once.
   $('input[name="' + this.name + '"]').not(this).attr("checked", false); //Removes 'checked' from HTML, but not table.
   $(this).attr("checked", true); //Marks 'checked' in HTML, but seemingly not DataTable.  
   var action = $(this).attr("value");
   var title = $(this).closest('tr').find('.name').text().trim();
   if ($(this).is(':checked')) {    
    console.log(title + " will be " + action)
   } else {
    $(this).attr("checked", false); //Removes checked from HTML, but seemingly not DataTable. 
    console.log(title + " will be removed.")
   }
});

function save() {
    var form_data  = table.rows().data(); //Prints out the DataTable as an array per row.  "checked=" always matches the source plist on disk.  
    console.log(form_data)
}

Thanks for any assistance.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,342Questions: 26Answers: 4,954
    Answer ✓

    gyrocode plugin, and think I have it set up right

    Looks like you are generating your own checkboxes. Using the Gyrocode plugin will problem conflict with the generated checkboxes.

    I suspect I need to update the DataTable when I click or unclick a checkbox

    Yes, see this FAQ. This Editor example shows one option to keep the checkbox values updates with data values of 1 or 0. This solution will work without the Editor. In this case the event handler at the bottom will need changed to update the cell's data to 1 or 0. What are you using to keep track of the checkbox state in the two plist files?

    If you don't want to keep a value like 1 / 0 for the checkbox state then use cell().node() to get the node to use jQuery / Javascript methods to determine the checked state.

    To help debug your code we will need to see a running test case.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    I would grab a sample of the generated HTML table and the relevant Javascript code and place use the following link to create the test case:
    https://live.datatables.net/

    Kevin

  • kthorngrenkthorngren Posts: 21,342Questions: 26Answers: 4,954

    If I refresh the page, the checkboxes are remembered and not reloaded from the file. I would like it to reload from the file.

    You aren't using Datatables to load the data. Its reading the generated table to load its data cache and display the Datatable. To verify this isn't a Datatables issue remove / comment out the Datatables init code. Do you still see that the checkboxes are remebered?

    Kevin

  • outage027outage027 Posts: 4Questions: 1Answers: 0

    Do you still see that the checkboxes are remebered?

    I commented out the DataTables init code, and my table is displaying without the DataTable features. Every page refresh shows the last value of the checkboxes. If I use Icognito mode, it displays the table based off of the data in my files.

    I never considered DataTables wasn't loading the data. When I see some of the HTML samples in the docs, I figured I needed to create HTML for the table to work, and when I saw my data in a proper looking DataTable I thought I did everything right.

    How can I tell that DataTables is reading in the data?

    I saw you provided more insight above, and I thank you for both answers. I will have to review that information, review your links and play around with it before I respond.

    One quick question on it however, do I need, or will I be better off using the Gyrocode plugin in my use case?

    Thank you!

  • kthorngrenkthorngren Posts: 21,342Questions: 26Answers: 4,954

    I never considered DataTables wasn't loading the data

    Datatables supports many different data sources. See the data docs for details.

    my table is displaying without the DataTable features. Every page refresh shows the last value of the checkboxes

    Are you saying the table table has paging available when not using Datatables? If yes then you possibly have another library controlling the table. Using Datatables with this might introduce conflicting table controls.

    How can I tell that DataTables is reading in the data?

    When you see the Datatable features and can properly search, sort and page the table then you will know Datatables read the HTML data.

    will I be better off using the Gyrocode plugin in my use case?

    The Gyrocode checkboxes plugin uses the Select extension for row selection. It sounds like you are using the checkboxes for setting specific data values for on/off. The Gyrocode checkboxes won't help with this.

    Kevin

  • outage027outage027 Posts: 4Questions: 1Answers: 0

    Are you saying the table table has paging available when not using Datatables? If yes then you possibly have another library controlling the table. Using Datatables with this might introduce conflicting table controls.

    No. There is no pagination or other features without the init.

    Thanks for the info on Gyrocode. I will focus on the built in features and will look closer at your example in the next few days.

  • outage027outage027 Posts: 4Questions: 1Answers: 0

    I realized I forgot to follow up and mark this closed.

    Thank you Kevin for your help.

    I ended up making a hidden column. When a user checks a checkbox, that column represents which of the three checkboxes is selected. When the user saves the data with a button, I can read the text in the hidden column to properly write the file.

    At this point the file and table are in sync. If the user clicks another element on the page which loads a table, it is from a file so it is up to date.

    So while I never figured out how to read/write checkboxes in the actual table, this seems to work perfectly fine.

Sign In or Register to comment.