Getting all selected rows with DataTables checkbox plugin with server side - javascript

I have this DataTable defenition:
var availableFilesTable = $("#availableFiles").DataTable({
'processing': true,
'serverSide': true,
'ajax': '#Url.Action("GetAllBinariesExclude", "Program", new {programId = Model.Id})',
'columns': [
{
data: 'Id',
'checkboxes': {
'selectRow': true
}
},
{
'data': 'BinaryName'
},
{ 'data': 'Sha1Hash' }
],
'select': {
'style': 'multi'
},
'order': [[1, 'asc']]
});
I want to get all the selected rows and submit them to server, I have the following code for form submit event:
$('form').submit(function(event) {
event.preventDefault();
var form = this;
var existingFileIds = selectedFilesTable.column(0).checkboxes.selected();
var fileIndex = 0;
var newFiles = availableFilesTable.column(0).checkboxes.selected();
$.each(newFiles,
function(index, fileId) {
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'SelectedBinaryFilesIds[' + fileIndex + ']')
.val(fileId)
);
fileIndex++;
});
if ($(form).valid()) {
form.submit();
}
});
The problem is that when I put a debugger and inspect the content of newFiles it only contains the content of active page of DataTable, Any hint on what am I doing wrong? I want to get all the selected rows in all pages with server side rendering but with the following code I only get the selected rows in the active page.
any help is much appreciated.

Related

TypeError - d is not defined

So I'm using jQuery child rows to display some data within a parent row. After displaying initially via Ajax, I do another ajax request and change data in the datatable. Now, if I try to expand it, it shows the rows. However, if I again try to change data in the datatable, it says d is not defined.
Here is my code when I initially load data in the datatable.
$.ajax({
url: "GetGridDetails?decodeID="+decoderFileSelected,
type: "GET",
dataType: 'json',
success: function (myData) {
if(myData != null){
console.log("my data is:"+myData);
var table = $('#dashNumTable').DataTable({
destroy: true,
data: myData ,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "S" },
{ "data": "W" },
{ "data": "SA" },
{ "data": "DDS" },
{ "data": "AAS" },
{ "data": "ABS" },
{ "data": "BIN" },
{ "data": "ET" }
],
"order": [[1, 'asc']]
});
// Add event listener for opening and closing details
$('#dashNumTable tbody').on('click', 'td.details-control', function () {
//alert("clicked plus!");
var tr = $(this).closest('tr');
var row = table.row(tr);
//var row = $('#dashNumTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
}//if code ends..
else{
alert("There are no base numbers for the selected decoder ring file...");
}
} //end of success function...
});
This generates table with a plus button to expand and minus button to contract.
Code to refresh and add new data when an ajax event is fired.
$(document).on("click", "#showHGAPartBtn", function(){
// clear the eixisting table contents
//alert("show button clicked!");
var decoderFileSelected = $("#decoderFile").val();
//$('#dashNumTable').empty();
// var clearTable = $('#dashNumTable').DataTable();
// clearTable.clear().draw();
//clearTable.rows().remove();
$('#dashNumTable').DataTable().ajax.reload();
//get the fresh data..
$.ajax({
url: "GetGridDetails?decodeID="+decoderFileSelected,
type: "GET",
dataType: 'json',
success: function (data) {
//if(myData != null){
//console.log("my data is:"+myData);
var table = $('#dashNumTable').DataTable({
// destroy: true,
cache: false,
processing: true,
data: data ,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "S" },
{ "data": "W" },
{ "data": "SA" },
{ "data": "DDS" },
{ "data": "AAS" },
{ "data": "ABS" },
{ "data": "BIN" },
{ "data": "ET" }
],
"order": [[1, 'asc']]
});
// Add event listener for opening and closing details
// $('#dashNumTable').on('click', 'tbody td.details-control', function () {
$('#dashNumTable').delegate('tbody td.details-control', 'click', function () {
//alert("clicked plus!");
var tr = $(this).closest('tr');
//table.ajax.reload();
var row = table.row(tr);
// alert("Row is :"+row);
//var row = $('#dashNumTable').DataTable().row(tr);
console.log(tr);
console.log(row);
console.log(row.child.isShown());
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
// }//if code ends..
// else{
// alert("There are no base numbers for the selected decoder ring file...");
//}
},
//end of success function...
error: function(response){
console.log(response);
}
});// end of AJAX call
Here is the format function, which returns error in second time.
function format (d) {
//alert(d.stringify);
//alert(JSON.stringify(d));
var rowSelectedBaseNumbers = d.HGA_BASE_NUMBERS;
// `d` is the original data object for the row
//alert(rowSelectedBaseNumbers);
var selectedBaseNumbersDropdown = $("#selBaseNumbers").val();
var initial = "<table cellpadding='0' cellspacing='0' class='innerDataTbl'><tr class='shown'> <th>Dash No.</th> <th>Heads</th>";
var finalReturn = "";
var endHeaders = "</tr>";
var middleContentHeaders = "";
//iterate over the base numbers now
for(var i=0;i< selectedBaseNumbersDropdown.length; i++){
middleContentHeaders += "<th>"+selectedBaseNumbersDropdown[i]+"</th>";
}
var beginTRCheckboxes = "<tr><td>"+d.DIGIT+0+","+d.DIGIT+1+"</td><td>Up,Dn</td>";
var endTRCheckboxes = "</tr>";
var endTable = "</table>";
//iterate over the total base numbers again to create respective checkboxes
var checkboxes = "";
for(var i=0;i< selectedBaseNumbersDropdown.length; i++){
//is the selected base number already selected?
if($.inArray(selectedBaseNumbersDropdown[i], rowSelectedBaseNumbers) == -1){
//not found
//display checkbox as it is
checkboxes += "<td><input type='checkbox'/></td>";
}
else{
//found
//mark checkbox already selected
checkboxes += "<td><input type='checkbox' checked='checked' disabled/></td>"
}
}
//generate final return now
finalReturn = initial+middleContentHeaders+endHeaders+beginTRCheckboxes+checkboxes+endTRCheckboxes+endTable;
return finalReturn;
}
The error returned is
typeerror - d is not defined
make a failSafe scenario in your format function for whenever no data is available, the code will not execute.
function format (d) {
if (d) { return null; }
...
}
Are you sure that the code
row.data()
actually returns a value? => Try to figure that out.
Also, what is d? Try to make your code as easy as possible to read. We developers are writers. Not for the computer, but for our colleagues who sometimes need to read our code to understand what we are trying to accomplish.

Jquery Datatables Checkbox selected append to input field

the btnSearchName will open a Modal with table of the search result, then it has checkbox per row to select, then after I click the btnSubmit, the Modal will close and must put the selected ssn_or_tin column in an input field like '123, 645, 936, 743', I already tried many codes but not working, please help
$('#btnSearchName').on("click", function() {
Namestable = $('#NamesDatatable').DataTable({
"processing": true,
'select': {
'style': 'multi'
},
'order': [[1, 'asc']],
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-6'i><'col-sm-6'p>>",
"ajax": {
"url": '/Home/GetAllCusname',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.name = $('#txtName').val();
}
},
"columns": [
{
defaultContent: '',
className: 'select-checkbox',
'checkboxes': {
'selectRow': true
},
orderable: false
},
{ "data": "ssn_or_tin", "autoWidth": true },
{ "data": "name", "autoWidth": true }
]
});
});
$('#btnSubmit').on("click", function () {
var rows_selected = Namestable.column(0).checkboxes.selected(); //i have not tested this line of code yet if it's working,
maybe there is another way of getting the selected checkbox, maybe by their class if they have the 'selected' class
$.each(rows_selected, function () {
$('#txtSSNTIN').append(
//I don't know what code to put here, it must append the
'ssn_or_tin' values like '123, 953, 673' in the input field with
the id 'txtSSNTIN'
);
});
});
You could have try Onrowbound in DataTable. You dont have to specify these things

Kendo Grid Acting Weird on Update

I have a kendo grid which is acting weirdly. I'm trying to select a row and update value in the data source. The grid has 2 rows: one template i.e. check box and one value in data source which is Boolean.
All I'm trying to do is:
When clicked on checkbox - Update the value of IsChecked in the data
source and mark the row as selected
The code below works fine but only after each check box is clicked at least once.
To replicate: Click on any checkbox, you'll see the value in the row gets updated, but check box is not checked. Click on it again and you'll see the check box gets checked and row gets selected. But never on first time. Same happens with all the rows. After 2nd run they work fine, but not at first.
Here is the Telerik fiddle link to play around
$("#grid").kendoGrid({
columns: [
{
title: "Check",
template: '<input class="checkbox" type="checkbox" />'
},
{ field: "IsChecked" }
],
dataSource: [
{ IsChecked:false},
{ IsChecked:false },
{ IsChecked:false },
{ IsChecked:false }
],
dataBound: function () {
$(".checkbox").bind("change", function (e) {
var row = $(e.target).closest("tr");
row.toggleClass("k-state-selected");
var grid = $("#grid").data("kendoGrid");
var index = $("tr", grid.tbody).index(row);
var data = grid.dataSource.at(index);
data.set("IsChecked", true);
});
}
});
Thank you
Try below code. Working fiddle http://dojo.telerik.com/UNIpU/3
$("#grid").kendoGrid({
columns: [{
title: "Check",
template: '<input class="checkbox" #= IsChecked ? \'checked="checked"\' : "" # type="checkbox" />'
},
{
field: "IsChecked"
}
],
dataSource: [{
IsChecked: false
}, {
IsChecked: false
}, {
IsChecked: false
}, {
IsChecked: false
}],
dataBound: function(e) {
var grid = e.sender;
var data = grid._data;
data.forEach(function(entry) {
if (entry.IsChecked) {
$('tr[data-uid="' + entry.uid + '"]').addClass("k-state-selected");
} else {
$('tr[data-uid="' + entry.uid + '"]').removeClass("k-state-selected");
}
})
}
});
$("#grid .k-grid-content").on("change", "input.checkbox", function(e) {
var grid = $("#grid").data("kendoGrid"),
dataItem = grid.dataItem($(e.target).closest("tr"));
dataItem.set("IsChecked", this.checked);
});

Change button color on page load based on field value

I'm using Datatables with X-editable and have some bootstrap buttons in a table. Basically if the user updates the editable 'Status' column to 'Resolved' I want the 'Not Validated' button in the previous row to turn yellow. If the status is switched back to any other status it should turn back to red.
I'm using Datatables grouping function to add the 'Not Validated' button and the color changing is working however, how do I check the value of the status field on page load and set the correct color?
I have a JSFiddle setup: http://jsfiddle.net/n74zo0ms/19/
JQuery:
//initialize the datatable
$(document).ready(function() {
var table = $('#dataTables').DataTable({
"columnDefs": [{
"visible": false,
"targets": 0
}],
"info": false,
"searching": false,
"drawCallback": function(settings) {
setupXedit();
var api = this.api();
var rows = api.rows({
page: 'current'
}).nodes();
var last = null;
api.column(0, {
page: 'current'
}).data().each(function(group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><th colspan="2"></i><i class="fa fa-arrow-circle-o-right"></i> Cluster: ' + group + '</th><th colspan="1"><i class="fa fa-exclamation-triangle fa-switch"></i> Not Validated</th></tr>'
);
last = group;
}
});
}
});
});
function setupXedit() {
//initialize the editable column
$('.status').editable({
url: '/post',
pk: 1,
source: [{
value: 'New',
text: 'New'
}, {
value: 'In Progress',
text: 'In Progress'
}, {
value: 'Resolved',
text: 'Resolved'
}],
title: 'Example Select',
validate: function(value) {
var cell = $(this).parent().parent().prev().find(".btn-switch");
var cell2 = $(this).parent().parent().prev().find(".fa-switch");
if (value == 'Resolved') {
cell.removeClass('btn-danger');
cell2.removeClass('fa-exclamation-triangle');
cell.addClass('btn-warning');
cell2.addClass('fa-thumbs-o-down');
} else {
cell.removeClass('btn-warning');
cell2.removeClass('fa-thumbs-o-down');
cell.addClass('btn-danger');
cell2.addClass('fa-exclamation-triangle');
};
}
});
}
Put this code above your other functions, right after your $(document).ready(function() {
$(".status").each(function(){
if($(this).text() === "Resolved"){
...do stuff....
..set color
..set text
}
});

Using jQuery, how to check whether a table cell is empty or not?

Using jQuery, how to check whether a table cell is empty or not?
Please help me.
What do you mean by empty.
//cell maycontain new lines,spaces,&npsp;,... but no real text or other element
$("cellselector").text().trim()=="";
or
//cell has no child elements at all not even text e.g. <td></td>
$("cellselector:empty")
You can use CSS selectors with the $ function to get a reference to the cell's element, and then use the html function to see whether it has any contents. For instance, if the cell has an ID "foo":
if ($("#foo").html()) {
// The cell has stuff in it
}
else {
// The cell is empty
}
Try this:
$content = $('#your_cell_id_here').html();
if($content == '')
{
// yes it is empty
}
else
{
// no it is not empty
}
You can use the trechnique I posted here
http://www.keithrull.com/2010/06/09/HowToChangeTableCellColorDependingOnItsValueUsingJQuery.aspx
You can use this if you already know the id of the cell you want to check
$valueOfCell = $('#yourcellid').html();
or you can iterate on the cells of the table
$("#yourtablename tr:not(:first)").each(function() {
//get the value of the table cell located
//in the third column of the current row
var valueOfCell = $(this).find("td:nth-child(3)").html();
//check if its greater than zero
if (valueOfCell == ''){
//place action here
}
else{
//place action here
}
});
You could add css classes to your table and its rows and columns, then use jquery selectors to get the table item:
if ( !($('#mytable tr.row-i td.column-j').html()) ) { alert("empty"); }
for datatables, you may use the following
var missedClockoutDataTable = $("#missedClockoutsDatatable").DataTable({
"order": [[0, "asc"]],
"serverSide": true,
"processing": true,
responsive: true,
destroy: true,
select: true,
fixedHeader: {
header: true,
headerOffset: $('#fixed').height()
},
buttons: [
{extend: 'copy', className: 'ui button'},
{extend: 'csv', className: 'ui button'},
{extend: 'excel', className: 'ui button'},
{extend: 'pdf', className: 'ui button'},
],
dom:
"<'row'<'col-sm-3'l><'col-sm-6 text-center'B><'col-sm-3'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
"ajax": {
"url": "{{url('workplace/dashboard/employees/missed-clockouts')}}",
data: function (d) {
d.gender = $("#gender").val();
d.roles = $("#roles").val();
},
},
"columns": [
{data: 'full_name', name: 'full_name'},
{data: 'clock', name: 'clock'},
{data: 'in', name: 'in'},
{data: 'out', name: 'out'},
{data: 'numberofHours', name: 'numberofHours'},
{data: 'clockoutReason', name: 'clockoutReason'},
{data: 'action', name: 'action'},
],
//when the table has fully loaded, proceed with looping through each row except the first one and then delete the rows if the IN column cell is empty
"initComplete": function(settings, json) {
// if the in type is empty, then hide that row
$("#missedClockoutsDatatable tr:not(:first)").each(function() {
//get the value of the table cell located
//in the third column of the current row
var valueOfCell = $(this).find("td:nth-child(3)").html();
//check if its greater than zero
if (valueOfCell == ''){
console.log(222);
this.remove();
}
});
}
});

Categories