I have this code below to click a checkbox in my DataTable and get the IDs and store in an array. For Example I have a 2 seperate DataTables First is for President and second is for the Senators.
We know that we can only vote 1 in President and for Senators we can choose many.
My problem here is I can check how many checkboxes in the DataTables. How to limit the checked checkboxes?.
Still learning in bootstrap here.
JS Code
var dataTablestest = $("#tbltest").DataTable({
responsive: true,
processing: true,
info: true,
search: true,
stateSave: true,
order: [[1, "asc"], [2, "asc"]],
lengthMenu: [[50, 100, 200, -1], [50, 100, 200, "All"]],
ajax: { "url": "/Voting/LoadTableTest" },
columns:
[
{ data: "testID", title: "", visible: false, searchable: false },
{ data: "Fullname", title: "FullName", sClass: "alignRight" },
{ data: "Position", title: "Position", sClass: "alignRight" },
{ data: "party", title: "Party", sClass: "alignRight" },
{ data: "ActionMenu", title: "Click to vote", searchable: false, orderable: false, sClass: "alignCenter",
"mRender": function (data) {
return '<center><label><input class="checkId" type="checkbox" id="chkvote_' + data + '" value=""/></label></center>';
}
}
]
});
var arrayIds = [];
$('#tbltest tbody').on('click', 'tr', function (e) {
if ($(e.target).is(".checkId")) {
var Ids = dataTablestest.row(this).data().testID;
arrayIds.push(Ids);
return
}
});
EDIT
I found an answer but there is a problem with it. My counter keeps increment every time I check a checkbox from my dataTable.
$('#tbltest tbody').on('click', 'tr', function (e) {
if ($(e.target).is(".checkId")) {
if ($(e.target).is(":checked") == true) {
CheckCount = CheckCount + 1;
var Ids = dataTablestest.row(this).data().testID;
if (CheckCount > 1) {
return false;
}
arrayIds.push(Ids);
return
}
else {
CheckCount = parseInt(CheckCount) - parseInt(1);
}
}
});
I use this code below.. Thanks to all who view my thread.
var arrayIds = [];
$('#tbltest tbody').on('click', 'tr', function (e) {
if ($(e.target).is(".checkId")) {
var Ids = dataTablestest.row(this).data().testID;
if ($(e.target).is(":checked") == true) {
var lenArray = arrayIds.length;
if (lenArray < 1) {
arrayIds.push(Ids);
} else {
return false;
}
}
else {
for (var i = arrayIds.length - 1; i >= 0; i--) {
if (arrayIds[i] === Ids) {
arrayIds.splice(i, 1);
}
}
}
}
return;
});
Related
Currently, I'm working on a datatable. In this datatable, we can modify the data of some columns.
But the problem is that once the user to modify a datum and that makes an interaction with the datatable that is to say "search, numberDisplay, ..." then the displayed data corresponds to the data of the AJAX request.
I'm on 1.11.1 version of "Jquery" and 1.9.4 for "dataTables"
Here is my code :
$(document).ready(function(){
var listeRespPosePlv = $('#listeRespPosePlv').val();
listeRespPosePlv = JSON.parse(listeRespPosePlv);
var listeRespPoseFormatted = [];
$(listeRespPosePlv).each(function(i, v){
listeRespPoseFormatted.push({'value': v.id_responsable_pose_plv, 'label': v.libelle});
});
$('#attribution_pose')[0].currentDataTable = $('#attribution_pose').dataTable({
"bProcessing": true,
"bServerSide": true,
"bStateSave": true,
'sAjaxSource': Router.url('campagne-plv-attribution'),
'aLengthMenu': [
[10, 25, 50, 1000, -1],
[10, 25, 50, 1000, "All"]
],
'iDisplayLength': 1000,
'fnServerParams' : function( aoData ) {
var idCampagnePlv = $('#id_campagne_plv').val();
aoData.push( { 'name': 'id_campagne_plv', 'value': idCampagnePlv } );
},
'fnDrawCallback': function(oSettings){
$('.datepicker').datepicker();
var table = this.fnGetData();
var test = $('#attribution_pose tbody tr');
for(var i = 0; i < table.length; i++){
for(var j = 0; j < table[i].length; j++){
if(table[i][j].localeCompare(test[i].cells[j].children[0].outerHTML) !== 0){
console.log('Diff');
}else{
console.log('Ok');
}
}
}
},
'oLanguage': {
'sUrl': Constante.get('base_full_url')+'assets/vendor/datatables/french.json'
}
}).columnFilter({
sPlaceHolder: "head:before",
aoColumns: [
{ type: "text" },
{ type: "text" },
{ type: "text" },
{ type: "text" },
{ type: "select" , values: listeRespPoseFormatted},
{ type: "text" },
{ type: "text" },
{ type: "text" },
null,
null,
null,
null,
{ type: "text" }
]
});
});
How can I avoid this?
Thank you for your help.
There is a data table with export to PDF or Excel and print buttons.But pagination doesn't appear. When I have looked examples most of them same as my project; when they put button, pagination doesn't appear. How can I solve the problem?
js code of Data table is below;
var oTable = $('#datatables').dataTable({
destroy: true,
"bSort": false,
dom: 'Bfrtip',
buttons: [
{
extend: 'excelHtml5',
footer: true ,
exportOptions: {
columns: [0, 1, 2, 3, 4,5,6,7]
}
},
{
extend: 'pdfHtml5',
exportOptions: {
columns: [0, 1, 2, 3, 4, 5]
},
customize: function (doc) {
//Remove the title created by datatTables
doc.content.splice(0, 1);
//Create a date string that we use in the footer. Format is dd-mm-yyyy
var now = new Date();
var jsDate = now.getDate() + '-' + (now.getMonth() + 1) + '-' + now.getFullYear();
// doc.pageMargins = [20, 60, 20, 30];
// Set the font size fot the entire document
doc.defaultStyle.fontSize = 9;
// Set the fontsize for the table header
doc.styles.tableHeader.fontSize = 9;
// Create a header object with 3 columns
// Left side: Logo
// Middle: brandname
// Right side: A document title
doc['header'] = (function () {
return {
columns: [
{
alignment: 'left',
italics: true,
text: 'dataTables',
fontSize: 18,
margin: [10, 0]
},
{
alignment: 'right',
fontSize: 14,
text: $("#drpIller option:selected").text() + " " + $("#drpIlceler option:selected").text()
}
],
margin: 20
}
});
doc['footer'] = (function (page, pages) {
return {
columns: [
{
alignment: 'left',
text: ['Oluşturulma tarihi: ', { text: jsDate.toString() }]
},
{
alignment: 'right',
text: ['page ', { text: page.toString() }, ' / ', { text: pages.toString() }]
}
],
margin: 20
}
});
var objLayout = {};
objLayout['hLineWidth'] = function (i) { return .5; };
objLayout['vLineWidth'] = function (i) { return .5; };
objLayout['hLineColor'] = function (i) { return '#aaa'; };
objLayout['vLineColor'] = function (i) { return '#aaa'; };
objLayout['paddingLeft'] = function (i) { return 4; };
objLayout['paddingRight'] = function (i) { return 4; };
doc.content[0].layout = objLayout;
}
},
{
extend: 'print'
}
],
"responsive": true,
"data": data,
"columns": [
{ "data": "A", "autoWidth": true},
{ "data": "S", "autoWidth": true},
{ "data": "D", "autoWidth": true },
{ "data": "E", "autoWidth": true},
{ "data": "F", "autoWidth": true },
{ "data": "G", "autoWidth": true }
],
"bAutoWidth": false
}
});
thanks your valuable for helps.
I found answer at this link:
https://codepen.io/RedJokingInn/pen/XMVoXL
It is abouth dom options.
It is solved When I write
"dom": '<"dt-buttons"Bf><"clear">lirtp'
instead
dom: 'Bfrtip'
tutorial at the link also consists printing page numbers and printing same sentence top of every pages informations.
May be can help someone in the future.
I have a grid (made with jqGrid 4.15.2). The code looks like the one below:
$.jgrid = $.jgrid || {};
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
$(function () {
"use strict";
var $grid = $("#list"),
maximizeGrid = function () {
var newWidth = $grid.closest(".ui-jqgrid").parent().width();
$grid.jqGrid("setGridWidth", newWidth, true);
};
// Resize grid if window is being resized
$(window).on("resize", maximizeGrid);
$grid.jqGrid({
colNames: ["", "Form #", "Form", "Plan", "Class", "Drug"],
colModel: [
{name: "act", template: "actions"},
{
name: "FormId",
align: 'center',
fixed: true,
frozen: true,
resizable: false,
width: 100,
editable: "hidden"
},
{name: "FormName", search: true, stype: "text"},
{name: "PlanName", search: true, stype: "text"},
{
name: "DrugGroupName",
edittype: "select",
editable: true,
search: true,
editoptions: {
dataUrl: "/ajax/drug_groups/get_all",
buildSelect: function (data) {
var select = "<select>", i;
for (i = 0; i < data.length; i++) {
select += "<option value='" + String(data[i].Id) + "'>" + $.jgrid.htmlEncode(data[i].DrugGroupName) + "</option>"
}
return select + "</select>";
},
selectFilled: function (options) {
setTimeout(function () {
$(options.elem).select2({
width: "100%"
});
}, 0);
}
},
stype: "select", searchoptions: {
sopt: ["eq", "ne"],
generateValue: true,
noFilterText: "Any",
selectFilled: function (options) {
setTimeout(function () {
$(options.elem).select2({
width: "100%"
});
}, 0);
}
}
},
{name: "DrugName", search: true, stype: "text"}
],
cmTemplate: {
width: 300,
autoResizable: true
},
iconSet: "fontAwesome",
rowNum: 25,
guiStyle: "bootstrap",
autoResizing: {
compact: true,
resetWidthOrg: true
},
rowList: [25, 50, 100, "10000:All"],
toolbar: [true, "top"],
viewrecords: true,
autoencode: true,
sortable: true,
pager: true,
toppager: true,
cloneToTop: true,
hoverrows: true,
multiselect: true,
multiPageSelection: true,
rownumbers: true,
sortname: "Id",
sortorder: "desc",
loadonce: true,
autowidth: true,
autoresizeOnLoad: true,
forceClientSorting: true,
prmNames: {id: "Id"},
jsonReader: {id: "Id"},
url: '/ajax/plans_to_forms/get_all',
datatype: "json",
editurl: '/ajax/plans_to_forms/update',
formDeleting: {
url: '/ajax/plans_to_forms/delete/',
delicon: [true, "left", "fa-scissors"],
cancelicon: [true, "left", "fa-times"],
width: 320,
caption: 'Delete Plan to Form Link',
msg: 'Are you sure you want to delete this link?',
beforeShowForm: function ($form) {
var rowids = $form.find("#DelData>td").data("rowids");
$form.closest(".ui-jqdialog").position({
of: window,
my: "center center",
at: "center center"
});
if (rowids.length > 1) {
$form.find("td.delmsg").html('Are you sure you want to delete all the selected form links?');
}
},
afterComplete: function (response, postdata, formid) {
if (response.responseText === "true") {
toastr["success"]("The link was deleted successfully.", "Information");
} else {
toastr["error"]("Something went wrong, the link could not be deleted.", "Error");
}
}
},
ajaxSelectOptions: {
type: "POST",
dataType: "json"
},
navOptions: {
edit: false,
add: false,
search: false
},
inlineEditing: {
keys: true,
focusField: "DrugGroupName",
serializeSaveData: function (postData) {
var changedData = {}, prop, p = $(this).jqGrid("getGridParam"),
idname = p.keyName || p.prmNames.id,
oldValue, cm;
for (prop in postData) {
oldValue = p.savedRow[0][prop];
if (p.iColByName[prop] != null) {
cm = p.colModel[p.iColByName[prop]];
}
if (postData.hasOwnProperty(prop) && (postData[prop] !== oldValue || prop === idname)) {
changedData[prop] = postData[prop];
}
}
return changedData;
},
aftersavefunc: function () {
toastr["success"]("The record was updated successfully.", "Information");
},
errorfunc: function () {
toastr["error"]("Something went wrong, the record could not be updated.", "Error");
}
},
onSelectRow: function (rowid, status, e) {
var $self = $(this),
$td = $(e.target).closest("tr.jqgrow>td"),
p = $self.jqGrid("getGridParam"),
savedRow = p.savedRow;
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
if ($td.length > 0 && $td[0].cellIndex !== p.iColByName.act) {
// don't start editing mode on click on "act" column
$self.jqGrid("editRow", rowid);
}
},
loadComplete: function () {
var $self = $(this), p = $self.jqGrid("getGridParam");
if (p.datatype === "json") {
// recreate the toolbar because we use generateValue: true option in the toolbar
$self.jqGrid("destroyFilterToolbar").jqGrid("filterToolbar");
}
}
}).jqGrid('navGrid').jqGrid("filterToolbar").jqGrid('setFrozenColumns');
// fill top toolbar
$('#t_' + $.jgrid.jqID($grid[0].id)).append($("<div><label for=\"globalSearchText\">Global search in grid for: </label><input id=\"globalSearchText\" type=\"text\"></input> <button id=\"globalSearch\" type=\"button\">Search</button></div>"));
$("#globalSearchText").keypress(function (e) {
var key = e.charCode || e.keyCode || 0;
if (key === $.ui.keyCode.ENTER) { // 13
$("#globalSearch").click();
}
});
$("#globalSearch").button({
icons: {primary: "ui-icon-search"},
text: false
}).click(function () {
var postData = $grid.jqGrid("getGridParam", "postData"),
colModel = $grid.jqGrid("getGridParam", "colModel"),
rules = [],
searchText = $("#globalSearchText").val(),
l = colModel.length,
i,
cm;
for (i = 0; i < l; i++) {
cm = colModel[i];
if (cm.search !== false && (cm.stype === undefined || cm.stype === "text")) {
rules.push({
field: cm.name,
op: "cn",
data: searchText
});
}
}
postData.filters = JSON.stringify({
groupOp: "OR",
rules: rules
});
$grid.jqGrid("setGridParam", {search: true});
$grid.trigger("reloadGrid", [{page: 1, current: true}]);
return false;
});
});
When I filter something and then want to mark the filtered results for delete all of them for some reason everything gets selected even those that hasn't been filtered which is sending all the IDs to the backend and therefore I am loosing everything when deleting based on the ID.
Maybe it's an stupid option or something else but I can't find what is wrong. Here is a video I have made showing up the issue. Here is a Fiddle for play with where you can see the issue happening
Steps to reproduce the issue:
Filter the column Filename by test
Using the first checkbox mark all of them
Without un-mark anything, remove the filter
Result: everything has been selected and therefore will be posted
Any ideas? Any help?
I find the problem, which you describe, very interesting and thus I changed the default behavior of "Select All" button (checkbox) to select only currently filtered data (see the commit). The new option selectAllMode with the value "all" allows to have the old behavior.
Your demo uses the latest free jqGrid directly from GitHub and thus it should work already like you want.
I am working on JQgrid and trying to achieve some specific functionality. These functionalists are
1)inline update with message shown before update.
2)Multiple update
I tried to read jqgrid and got this code https://jsfiddle.net/OlegKi/byygepy3/11/ . Which is quite approximate to my requirement but it doesn't contain multiple update and message shown before update.
I tried to overwrite these code but maximum i reached is this https://jsfiddle.net/byygepy3/72/ but failed because multiple update only updating half of record and it doesn't show any message before updating either single row or multiple row.
code is inserting just allow me to ask question.
$(function () {
var myData = [
{ id: 10, ParameterName: "Test", ParameterValue: "" },
{ id: 20, ParameterName: "Test 1", ParameterValue: "" },
{ id: 30, ParameterName: "Test 2", ParameterValue: "" },
{ id: 40, ParameterName: "Test 2", ParameterValue: "" },
{ id: 50, ParameterName: "Test 2", ParameterValue: "" },
{ id: 60, ParameterName: "Test 2", ParameterValue: "" }
],
$grid = $("#list");
// change the text displayed on editrules: {required: true }
$.extend(true, $.jgrid.locales["en-US"].edit.msg, {
required: "No value was entered for this parameter!!!"
});
$grid.jqGrid({
datatype: "local",
data: myData,
colNames: ["", "Parameter Name", "Parameter Value"],
colModel: [
{ name: "act", template: "actions" }, // optional feature
{ name: "ParameterName" },
{ name: "ParameterValue", editable: true,
editoptions: { maxlength: 100 }, editrules: {required: true } }
],
cmTemplate: { autoResizable: true },
autoResizing: { compact: true },
pager: true,
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: true, // disable current view record text like 'View 1-10 of 100'
sortname: "Name",
iconSet: "fontAwesome",
caption: 'Parameters',
autowidth: true,
hidegrid: false,
inlineEditing: {
keys: true
},
singleSelectClickMode: "selectonly", // prevent unselect once selected rows
beforeSelectRow: function (rowid) {
// allow selection if saving successful
},
onSelectRow: function (rowid) {
$(this).jqGrid("editRow", rowid);
},
afterSetRow: function (options) {
var item = $(this).jqGrid("getLocalRow", options.rowid);
if (item != null) {
item.dirty = true;
}
},
navOptions: {
edit: false,
add: false,
search: false,
deltext: "Delete",
refreshtext: "Refresh"
},
inlineNavOptions: {
save: false,
savetext: "Save",
cancel: false,
restoreAfterSelect: false
},
formDeleting: {
// delete options
url: window.g_baseUrl + 'MfgTransactions_MVC/COA/Delete?',
beforeSubmit: function () {
// get value
var selRowId = $(this).jqGrid('getGridParam', 'selrow');
var parametricValue = $(this).jqGrid('getCell', selRowId, 'ParameterValue');
// check if empty
if (parametricValue === "") {
return [false, "Cannot delete: No value exists for this parameter"];
}
return [true, "Successfully deleted"];
},
delData: {
batchId: function () {
return $("#BatchId").val();
}
},
closeOnEscape: true,
closeAfterDelete: true,
width: 400,
msg: "Are you sure you want to delete the Parameter?",
afterComplete: function (response) {
if (response.responseText) {
alert("response.responseText");
}
//loadBatchListIntoGrid();
}
}
}).jqGrid('navGrid')
.jqGrid('inlineNav')
.jqGrid('navButtonAdd', {
caption: "Save Changed",
buttonicon: "fa-floppy-o",
onClickButton: function () {
var $self = $(this), i,
// savedRows array is not empty if some row is in inline editing mode
savedRows = $self.jqGrid("getGridParam", "savedRow");
for (i = 0; i < savedRows.length; i++) {
$self.jqGrid("saveRow", savedRows[i].id);
}
var localData = $(this).jqGrid("getGridParam", "data"),
dirtyData = $.grep(localData, function (item) {
return item.dirty;
});
alert(dirtyData.length > 0 ? JSON.stringify(dirtyData) : "no dirty data");
}
});
// make more place for navigator buttons be rwducing the width of the right part
var pagerIdSelector = $grid.jqGrid("getGridParam", "pager");
$(pagerIdSelector + "_right").width(100);
// make the grid responsive
$(window).bind("resize", function () {
$grid.jqGrid("setGridWidth", $grid.closest(".container-fluid").width());
}).triggerHandler("resize");
});
Free jqGrid supports a lot of callbacks, which will be used during saving the rows. You can use for example beforeSaveRow callback of inline editing, custom validation via editrules.custom callback function, beforeSelectRow and other. Additionally, your code seems to distinguish the initial empty value "" of ParameterValue column from any other values. The final code you should made yourself. I posted an example
beforeSelectRow: function (rowid) {
// allow selection if saving successful
var $self = $(this), i,
savedRows = $self.jqGrid("getGridParam", "savedRow");
for (i = 0; i < savedRows.length; i++) {
if (rowid !== savedRows[i].id) {
if (allowSaving.call(this, savedRows[i].id)) {
$self.jqGrid("saveRow", savedRows[i].id);
} else {
$self.jqGrid("restoreRow", savedRows[i].id);
}
}
}
return true;
},
with allowSaving function defined as
var allowSaving = function (rowid) {
var item = $(this).jqGrid("getRowData", rowid);
if (item.ParameterValue !== "") {
return confirm("Do you want to save \"" +
item.ParameterValue + "\" value in \"" +
item.ParameterName + "\"?");
} else {
return false;
}
};
It allows to ask the user to confirm the changes of ParameterName. Additionally the code of "Save Changed" button should be adjusted too.
See https://jsfiddle.net/OlegKi/byygepy3/74/
I am trying to change the background color of selected row(s) in jquery datatable using my own css class but, the tick mark in the checkbox is not appearing.
If I remove className: 'selected-row' from the below code, then everything works normal but, without the color I want.
Fiddler: https://jsfiddle.net/8f63kmeo/12/
HTML:
<table id="CustomFilterOnTop" class="table table-bordered table-condensed" width="100%"></table>
JS
var Report4Component = (function () {
function Report4Component() {
//contorls
this.customFilterOnTopControl = "CustomFilterOnTop"; //table id
//data table object
this.customFilterOnTopGrid = null;
//variables
this.result = null;
}
Report4Component.prototype.ShowGrid = function () {
var instance = this;
//create the datatable object
instance.customFilterOnTopGrid = $('#' + instance.customFilterOnTopControl).DataTable({
columns: [
{ title: "<input name='SelectOrDeselect' value='1' id='ChkBoxSelectAllOrDeselect' type='checkbox'/>" },
{ data: "Description", title: "Desc" },
{ data: "Status", title: "Status" },
{ data: "Count", title: "Count" }
],
"paging": true,
scrollCollapse: true,
"scrollX": true,
scrollY: "300px",
deferRender: true,
scroller: true,
dom: '<"top"Bf<"clear">>rt <"bottom"<"Notes">i<"clear">>',
buttons: [
{
text: 'Load All',
action: function (e, dt, node, config) {
instance.ShowData(10000);
}
}
],
columnDefs: [{
orderable: false,
className: 'select-checkbox text-center',
targets: 0,
render: function (data, type, row) {
return '';
}
}],
select: {
style: 'multi',
selector: 'td:first-child',
className: 'selected-row'
}
});
};
Report4Component.prototype.ShowData = function (limit) {
if (limit === void 0) { limit = 100; }
var instance = this;
instance.customFilterOnTopGrid.clear(); //latest api function
instance.result = instance.GetData(limit);
instance.customFilterOnTopGrid.rows.add(instance.result.RecordList);
instance.customFilterOnTopGrid.draw();
};
Report4Component.prototype.GetData = function (limit) {
//structure of the response from controller method
var resultObj = {};
resultObj.Total = 0;
resultObj.RecordList = [];
for (var i = 1; i <= limit; i++) {
resultObj.Total += i;
var record = {};
record.Description = "This is a test description of record " + i;
record.Status = ["A", "B", "C", "D"][Math.floor(Math.random() * 4)] + 'name text ' + i;
record.Count = i;
resultObj.RecordList.push(record);
}
return resultObj;
};
return Report4Component;
}());
$(function () {
var report4Component = new Report4Component();
report4Component.ShowGrid();
report4Component.ShowData();
});
function StopPropagation(evt) {
if (evt.stopPropagation !== undefined) {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
}
Issue:
Any suggestion / help will be greatly appreciated.
It's the class selected that sets the checkbox tick etc. and by using a different class the selected class is no longer added.
You can just add both those classes instead, and it should work
select: {
style: 'multi',
selector: 'td:first-child',
className: 'selected-row selected'
}
FIDDLE