Search code examples
datatables

JQuery Datatables set a different column value when a checkbox is selected in same row


I am using latest .Net core and Datatables in my app. I have the triggers set in the javascript for a adding a checkbox to column 1 (0) of the table and I also have a "select all" functioning on the column header and the intermediate status showing on the header. That all works great.

The data is for a list of pharmacies, the amount billed and the actual amount paid. I would like to click the checkbox for the pharmacy and then automatically fill in the amount paid cell with the full amount of the amount billed cell. Conversely, blank out the paid amount if pharmacy is unchecked.

cb Pharmacy Billed Paid
X pharm1 100 100
pharm2 200 0
pharm3 300 0
X pharm4 400 400

Code for the checkboxes was straight from datatables site and is below :

    // Handle click on "Select all" control
    $('#pharmacyTable-select-all').on('click', function () {
            // Check/uncheck all checkboxes in the table
            var rows = pharmacyTable.rows({ 'search': 'applied' }).nodes();
            $('input[type="checkbox"]', rows).prop('checked', this.checked);
        });

    // Handle click on checkbox to set state of "Select all" control
    $('#pharmacyTable tbody').on('change', 'input[type="checkbox"]', function () {
            // If checkbox is not checked
            if (!this.checked) {
                var el = $('#pharmacyTable-select-all').get(0);
                // If "Select all" control is checked and has 'indeterminate' property
                if (el && el.checked && ('indeterminate' in el)) {
                    // Set visual state of "Select all" control
                    // as 'indeterminate'
                    el.indeterminate = true;
                }
            }
        });

What needs to change for this functionality?


Solution

  • if you are not using the datatables templates and server side loading and just applying it to a prebuilt table, you can add a unique identifier for the row in the markup for the checkbox, the "Billed" source, and "paid" destination so that you can (using a data attribute data-row-id=XXX):

    1. associate the change event on all checkboxes in the table in document.ready
    2. in the event handler for the change event, read the data-row-id value
    3. locate the paid source var amount = $("span[data-row-id=XXX]).text()
    4. assign to the paid input $("input[data-row-id=XXX]).val(amount);