I have this MVC structure accessing the data from the model in a datatable. Each row consists of two td, one td is displaying text from the model's status field and another td is displaying checkbox value as a toggle from the model's isactive field. I wanted to use jQuery to detect the checkbox change and capture the data of the whole row in an array like [status,isactive] . Unfortunately I cannot detect the checkbox value whenever it is getting clicked. Using the .prop() always gives false values, it doesn't change with change of checkbox checking.
Mapping.cshtml:
<div id="StatusDiv" class="col-sm-12 col-md-6 form-horizontal">
<table id="StatusTable" class="table table-striped table-condensed acccDataTables">
<thead>
<tr>
<th id="StatusCol">Status</th>
<th id="ActiveCol">Is Active</th>
</tr>
</thead>
<tbody id="tbodyStatus">
@foreach (var item in Model.xStatuses) {
var chkid = "chk" + item.IsActive;
var tdid = "td" + item.AgentStatus;
<tr id="statusRow">
<td id="@tdid">@item.AgentStatus</td>
<td><input id="@chkid" type="checkbox" checked="@item.IsActive"
data-role="flipswitch" class="StatusToggle checkbox-based-flipswitch" />
<br />
</td>
</tr>
}
</tbody>
</table>
<button hidden class="btn btn-success btn-save-edit" id="saveStatusEdit">
<i>`save`</i>Save Settings
</button>
Edit.js
$(document).ready(function () {
var rows_selected = [];
var table = $("#StatusTable").DataTable({dom:'tpli',
fnInitComplete : function() {
if ($(this).find('tbody tr').length<=1) {
$(this).parent().hide();
},
fnDrawCallback: function() {
hideStatusBasics();
}
});
$('#StatusTable').on('click', 'td,input[type="checkbox"]', function (e) {
alert("Hey");
var $row = $(this).closest('tr');
var changeit = $('#StatusTable input[type="checkbox"]').prop('checked');
console.log(changeit);// Get row data
var data = table.row($row).data()[1];
console.log(data);/* Get row ID
var rowId = data[0]; // Determine whether row ID is in the list of selected row IDs
var index = $.inArray(rowId, rows_selected); // If checkbox is checked and row ID is not in list of selected row IDs
if (this.checked && index === -1) {
rows_selected.push(rowId);
// Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
} else if (!this.checked && index !== -1) {
rows_selected.splice(index, 1);
}// Prevent click event from propagating to parent
e.stopPropagation();*/
});
});
$('#StatusTable input[type="checkbox"]')is an array,you can get all the checkboxes inStatusTablewith the code.If you want to detect the checkbox whenever it is getting clicked.You can try to use: