Checkbox Clicked Event

Checkbox Clicked Event

jcziembojcziembo Posts: 4Questions: 1Answers: 0
edited February 2021 in Free community support

Hi, I am using datatables in my MVC applicaiton and I am having an issue with checkboxes. Here is what I am trying to do. I have my datatable which also has a check box at the end called confirm. What I need to do is:

When status is LIKE Plan use bool is_confirmed_plan else use bool is_confirmed_pull. If the value is false the checkbox is unchecked, if true the checkbox is checked. So when the user checks or unchecks the checkbox the value would change. This way when I submit the data to my controller I have the correct true/false values in these fields. I have tried many ways to render and while I can get the check box to appear and check it or uncheck it, the values remain unchanged when I submit to the controller. I assume I am missing a step when the render column value would change based on the users click.

Currently I am just trying to get the is_confirmed_plan to actually work before trying to figure out how to arrange so that if confirmationstatus is like PULLuse a different value.

All of this worked before I switched to datatables and I was grabbing the rows from the model. And submitting it as a Html.BeginForm to the controller which was taking a List<ConfirmationDto>

                            foreach (var item in Model.confirmations)
                            {
                                     <td>
                                        <div class="checkbox" >
                                            @if (item.StatusType == "PLAN")
                                            {
                                                @Html.CheckBoxFor(modelItem => modelItem.confirmations[i].is_confirmed_plan, htmlAttributes: new { id = "q1yes", })

                                            }
                                            else
                                            {
                                                @Html.CheckBoxFor(modelItem => modelItem.confirmations[i].is_confirmed_pull, htmlAttributes: new { id = "q2yes" })
                                            }
                                        </div>
                                    </td>
                             }

Of course I can't use this way anymore. Search box didn't work.

Here is some of the code.

    <script>

            
        var datajson = @Html.Raw(JsonConvert.SerializeObject(Model));
        $(document).ready(function () {
             var table = $('#CrossTable').DataTable({
                    fixedHeader: true,
                                     "ajax": {
                                        "url": "@Url.Action("ConfirmationsJson", "ControllerName")",
                                        "type": "GET",
                                         "dataType": "JSON",
                                         "contentType":"application/json; charset=utf-8",
                                         "data": { jsonInput : JSON.stringify(datajson)}
                                    },
                    "columns": [
                        {"data": "drv_con_id", 'className': "hidecol" },
                        {"data": "ordernumber"},                      
                        {"data": "EventTime_string"},                   
                        { "data": "confirmationStatus" },
                        {
                            "data":"is_confirmed_plan",
                            "render": function (data, type, row) {
                                if (data) {
                                    return '<input type="checkbox" name="is_confirmed_plan" class="editor-active" onclick="return "false";" checked>';
                                } else {
                                    return '<input type="checkbox" name="is_confirmed_plan" onclick="return "true";" class="editor-active">';
                                }                                
                            }
                        }
                        
                 ]
        });
    
********************************************this json post took me hours to figure out, but it works*********    
        $('#btnOK').click(function () {          
            
            var dataj = JSON.stringify(table.rows().data().toArray());
                $.ajax({
                    url: '@Url.Action("SubmitChanges","ControllerName")',
                    type: "POST",
                    dataType: 'JSON',
                    //contentType: "application/json; charset=utf-8",
                        data: { jsonInput: dataj }
                });

            });
        });
    </script>

**********************Controller*********

public async Task<ActionResult> SubmitChanges(string jsonInput)
{
var confirmations = JsonConvert.DeserializeObject<List<ConfirmationDto>>(jsonInput, new JsonSerializerSettings
                {
                    DateTimeZoneHandling = DateTimeZoneHandling.Local
                });

----Do stuff
}
 public class ConfirmationDto
{
public string confirmationStatus { get; set; }
        public bool is_confirmed_plan { get; set; }


        public bool is_confirmed_pull { get; set; }
}

Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,158Questions: 1Answers: 10,405 Site admin

    Of course I can't use this way anymore. Search box didn't work.

    That method would still work with DataTables - it can progressively enhance an HTML table. It doesn't need to Ajax load the data. However:

    the values remain unchanged when I submit to the controller.

    This is because you are using rows().data(), which is the original data that was used to populate the table. It does not reflect the live DOM values of input elements such as a checkbox. You need to specifically get those values - for example:

    var data = table
      .cells(null, -1)      // Get all cells in the last column
      .nodes()              // Get their `td` nodes
      .map(function(td) {   // Remap into an array of values
        return $('input', td).prop('checked');
      })
      .toArray();           // Convert to plain array
    

    Allan

  • jcziembojcziembo Posts: 4Questions: 1Answers: 0
    edited February 2021

    Thank you for the response. Unfortunately I am not very good with Javascript. I put your code into my

     $('#btnOK').click(function () {         
                var dataj = JSON.stringify(table
                    .cells(null, -1)      // Get all cells in the last column
                    .nodes()              // Get their `td` nodes
                    .map(function (td) {   // Remap into an array of values
                        return $('input', td).prop('checked');
                    })
                    .toArray());
                //var dataj = JSON.stringify(table.rows().data().toArray());
                    $.ajax({
                        url: '@Url.Action("SubmitChanges","ControllerName")',
                        type: "POST",
                        dataType: 'JSON',
                        //contentType: "application/json; charset=utf-8",
                            data: { jsonInput: dataj }
                    });
    
                });
    

    So I could see how that data looks. It looks like this: [true,true,false,false,false,false,false,true] (there were 8 rows). But I am not sure how do I update the values in var dataj = JSON.stringify(table.rows().data().toArray()); so that when I submit to my controller I have the values? This is what I need submitted to the server and I get it just fine with var dataj = JSON.stringify(table.rows().data().toArray());

    [{
            "drv_con_id": 0,
            "Legnumber": 9601891,
            "EventTime": "/Date(1613156400000)/",
            "EventTime_string": "2021/02/12 14:00",
            "TripType": "Pickup",
            "confirmationStatus": "UNCONFIRMED PLAN",
            "StatusType": "PLAN",     
            "is_confirmed_plan": false,
            "is_confirmed_pull": false        
        }, {
            "drv_con_id": 0,
            "Legnumber": 9602194,
            "EventTime": "/Date(1613242800000)/",
            "EventTime_string": "2021/02/13 14:00",
            "TripType": "Pickup",       
            "confirmationStatus": "UNCONFIRMED PLAN",
            "StatusType": "PLAN",      
            "is_confirmed_plan": false,
            "is_confirmed_pull": false
            
        }
    ]
    

    Keep in mind that my checkbox has to use is_confirmed_plan or is_confirmed_pull depending on what the confirmationStatus says. If Plan use is_confirmed_plan else use is_confirmed_pull .

    Somehow I have to loop through the table, check if the value is used in the box was is_confirmed_plan or is_confirmed_pull then see if it is checked. update the value. then JSON.stringify(table.rows().data().toArray()) the updated table to be sent off to the controller.

    Based on the example you gave I dont understand how I would go about updating the values before I send them off to the controller.

    Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • jcziembojcziembo Posts: 4Questions: 1Answers: 0
    edited February 2021
    var data = table
      .cells(null, -1)      // Get all cells in the last column
      .nodes()              // Get their `td` nodes
      .map(function(td) {   // Remap into an array of values
        return $('input', td).prop('checked');
      })
      .toArray();  
    

    Is there a way to use your above code to put the entire table into an array? Just like what this is doing var dataj = JSON.stringify(table.rows().data().toArray());?

    This gets all of the columns and rows, just not the updated data, while your gets the updated checkbox values, but nothing else. I have tried to research this .map thing and cant find anything useful.

  • allanallan Posts: 63,158Questions: 1Answers: 10,405 Site admin
    Answer ✓

    How about something like this:

    var data = [];
    table
      .rows()
      .every(function() {         // For every row
          var row = this.data();  // Get the data
          var cell = table.cell(this.index(), -1).node(); // And the checkbox cell
    
          row.is_confirmed_plan = $('input', cell).prop('checked'); // Get the checked state
    
          data.push(row); // Add to data array
      });  
    

    Allan

  • jcziembojcziembo Posts: 4Questions: 1Answers: 0

    Thanks for the info. I tried your idea and I think it might work. I updated my code that sends the table data to the controller and looks like the update comes through. I will have to play around more to make sure it works.
    Thanks a lot dude.
    Updated Code:

        var datajson = @Html.Raw(JsonConvert.SerializeObject(Model));
        $(document).ready(function () {
             var table = $('#CrossTable').DataTable({
                 fixedHeader: true,
                 "processing": true,
                                     "ajax": {
                                        "url": "@Url.Action("ConfirmationsJson", "ControllerName")",
                                        "type": "GET",
                                         "dataType": "JSON",
                                         "contentType":"application/json; charset=utf-8",
                                         "data": { jsonInput: JSON.stringify(datajson) },
                                         "error": function () {
                                             alert("Error: Failed to get data")
                                         }
                                    },
                    "columns": [
                        {"data": "drv_con_id", 'className': "hidecol" },
                        {"data": "ordernumber"},
                        {"data": "Legnumber"},
                        {"data": "EventTime_string"},
                        {"data": "TripType"},
                        { "data": "TripDescription", 'className': "table-text"},
                        {"data": "driverid"},
                        {"data": "DriverDispatchTerminal",'className': "hidecol"},
                        {"data": "TerminalName"},
                        { "data": "DBoard"},
                        {"data": "ConfirmPlanBy", 'className': "hidecol"},
                        {"data": "ConfirmedPlanDate_string", 'className': "hidecol"},
                        {"data": "ConfirmPullBy", 'className': "hidecol"},
                        {"data": "ConfirmPullDate_string", 'className': "hidecol"},
                        { "data": "confirmationStatus" },                                        
                        {
                            "data": null,'orderable':false,
                            "render": function (data, type, row) {
                                if (row.is_confirmed_plan || row.is_confirmed_pull) {
                                    return '<input type="checkbox" class="checkingbox"  onclick="return "false";" checked>';
                                } else {
                                    return '<input type="checkbox" class="checkingbox" onclick="return "true";" class="editor-active">';
                                }                                
                            }
    
                        }
    
                 ],
                 "language": {
                     'loadingRecords': '&nbsp;',
                     'processing': '<i class="spinner-border spinner-border-sm"  aria-hidden="true"></i> Loading...'
                 }
        });
    
        $('#btnOK').click(function () {            
            var data = [];
            table
                .rows()
                .every(function () {         // For every row
                    var row = this.data();  // Get the data
                    var cell = table.cell(this.index(), -1).node(); // And the checkbox cell
                    if (row.StatusType == "PLAN") {
                        row.is_confirmed_plan = $('input', cell).prop('checked'); // Get the checked state
                    }
                    if (row.StatusType == "PULL") {
                        row.is_confirmed_pull = $('input', cell).prop('checked'); // Get the checked state
                    }
                    data.push(row); // Add to data array
                });             
    
            //var dataj = JSON.stringify(table.rows().data().toArray());
                $.ajax({
                    url: '@Url.Action("SubmitChanges","Operations")',
                    type: "POST",
                    dataType: 'JSON',
                    //contentType: "application/json; charset=utf-8",
                    data: { jsonInput: JSON.stringify(data) },
                    success: function (res) {                     
                        if (res == 'success') {
                            $.notify('Successfuly Added', { globalPosition: 'top center', className: 'success' });
                        }
                        else {
                            $.notify('Failed To Add', { globalPosition: 'top center', type: "danger" });
                        }
                    }                   
    
                }).done(function () {                   
                    table.ajax.reload();                   
                })
        });
    
            //function SubmitFailure() {               
            //    $.notify('Failed To Add', { globalPosition: 'top center', type: "danger" });
            //    table.ajax.reload();
            //}
        });
    
This discussion has been closed.