I am using data tables. Currently, it is working as expected, hower I would like to have the Add and Remove Buttons have some sort of count. For example AddButton_0
How would I do this using Data Tables?
var url = "/ClientSetup/GetCatalogueContracts";
var contractsTable = $('#catalogueContractsTable').DataTable({
sAjaxSource: url,
columns: [
{ "data": "ID" },
{ "data": "Selected"},
{ "data": "Name"},
{ "data": "ContractType"},
{ "data": "StartDate"},
{ "data": "TerminationDate"},
{ "button": "Action" }
],
serverSide: true,
sDom: 't<"dt-panelfooter clearfix"ip>',
pageLength: pageSize,
bSort: false,
bLengthChange: false,
bSearch: true,
paging: true,
searching: true,
order: [[2, "asc"]],
language: {
emptyTable: "No contracts found.",
zeroRecords: "No contracts found.",
info: "_START_ to _END_ of _TOTAL_",
paginate: {
first: "First",
previous: "Previous",
next: "Next",
last: "Last"
}
},
columnDefs: [
{
targets: [0],
visible: false
},
{
targets: [1],
visible: false
},
{
targets: [2]
},
{
targets: [3],
sClass: "hidden-xs hidden-sm contractType"
},
{
targets: [4],
sClass: "hidden-xs fromDate"
},
{
targets: [5],
sClass: "hidden-xs terminationDate"
},
{
data: null,
targets: [6],
sClass: "updateTableRow text-center",
render: function ( data, type, full, meta )
{
var id = data["ID"];
return `<button class=\"btn btn-success br2 btn-xs fs12 table-btn button-selector-${id}\" id=\"AddContractBtn\">Add</button>`;
}
}
],
drawCallback: function( settings ) {
disableInvalidContracts();
},
autoWidth: false
});
// make sure already selected rows cannot be added again.
var excludeIds = getExcludeIds();
$.each(excludeIds, function() {
var button = $("#AddContractBtn.button-selector-" + this);
button.addClass("disabled");
button.prop('disabled', true);
});
}
#* Adding and Removing Data from both Tables *#
contractsTable.on('click', '#AddContractBtn', function () {
var $row = $(this).closest("tr");
#*Track Contract IDs that have been removed from the unselected table*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids.push($row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
var addRow = contractsTable.row($row);
var data = addRow.data();
data.Selected = true;
selectedContractsTable.row.add(addRow.data()).draw( false );
setSelectedInputForContract('true', data.ID);
disableInvalidContracts();
});
selectedContractsTable.on('click', '#RemoveContractBtn', function () {
var $row = $(this).closest('tr');
var addRow = selectedContractsTable.row($row);
var data = addRow.data();
data.Selected = false;
addRow.data(data);
addRow.remove().draw();
#* Remove the Contract ID from the exclide ids hidden input*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids = ids.filter(i => i !== $row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
setSelectedInputForContract('false', data.ID);
disableInvalidContracts();
});
I am looking for a way that I can add a Count for each of the buttons for example `AddButton_0 I am unsure if there is an option to use a count on DataTables. Or whether I could use JQuery?
Try this : you can have global variable and increment it for each access of button creation function. Click handler for add and remove button can be created with start with attribute selector in jquery.
See below code
var count = 0;
var url = "/ClientSetup/GetCatalogueContracts";
var contractsTable = $('#catalogueContractsTable').DataTable({
sAjaxSource: url,
columns: [
{ "data": "ID" },
{ "data": "Selected"},
{ "data": "Name"},
{ "data": "ContractType"},
{ "data": "StartDate"},
{ "data": "TerminationDate"},
{ "button": "Action" }
],
serverSide: true,
sDom: 't<"dt-panelfooter clearfix"ip>',
pageLength: pageSize,
bSort: false,
bLengthChange: false,
bSearch: true,
paging: true,
searching: true,
order: [[2, "asc"]],
language: {
emptyTable: "No contracts found.",
zeroRecords: "No contracts found.",
info: "_START_ to _END_ of _TOTAL_",
paginate: {
first: "First",
previous: "Previous",
next: "Next",
last: "Last"
}
},
columnDefs: [
{
targets: [0],
visible: false
},
{
targets: [1],
visible: false
},
{
targets: [2]
},
{
targets: [3],
sClass: "hidden-xs hidden-sm contractType"
},
{
targets: [4],
sClass: "hidden-xs fromDate"
},
{
targets: [5],
sClass: "hidden-xs terminationDate"
},
{
data: null,
targets: [6],
sClass: "updateTableRow text-center",
render: function ( data, type, full, meta )
{
var button = `<button class=\"btn btn-success br2 btn-xs fs12 table-btn button-selector-${id}\" id=\"AddContractBtn' + count + '\">Add</button>`;
count++; // increment count
var id = data["ID"];
return button;
}
}
],
drawCallback: function( settings ) {
disableInvalidContracts();
},
autoWidth: false
});
// make sure already selected rows cannot be added again.
var excludeIds = getExcludeIds();
$.each(excludeIds, function() {
var button = $("#AddContractBtn.button-selector-" + this);
button.addClass("disabled");
button.prop('disabled', true);
});
}
#* Adding and Removing Data from both Tables *#
contractsTable.on('click', 'button[id^=AddContractBtn]', function () {
var $row = $(this).closest("tr");
#*Track Contract IDs that have been removed from the unselected table*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids.push($row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
var addRow = contractsTable.row($row);
var data = addRow.data();
data.Selected = true;
selectedContractsTable.row.add(addRow.data()).draw( false );
setSelectedInputForContract('true', data.ID);
disableInvalidContracts();
});
selectedContractsTable.on('click', 'button[id^=RemoveContractBtn]', function () {
var $row = $(this).closest('tr');
var addRow = selectedContractsTable.row($row);
var data = addRow.data();
data.Selected = false;
addRow.data(data);
addRow.remove().draw();
#* Remove the Contract ID from the exclide ids hidden input*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids = ids.filter(i => i !== $row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
setSelectedInputForContract('false', data.ID);
disableInvalidContracts();
});
Related
I have datatable Like this
oInnerTable = $("#url_table_" + rotator_id).DataTable({
"processing": true,
"serverSide": true,
rowReorder: {
dataSrc: [1]
},
"ajax":{
url :"actions/data_url_response.php",
type: "post",
data: function ( d ) {
var url_status = $('.url_status').val();
d.rotator_id = rotator_id;
d.url_status = url_status;
}
},
autoWidth: false,
columnDefs: [
{ "visible": false, "targets": 0 },
{ orderable: true, className: 'reorder', targets: 0 },
{
"targets":[0, 7],
"orderable":false,
},
{
targets: 0,
render: function (data, type, row) {
return '<div class="form-check"><input type="checkbox" class="form-check-input position-static select_ids" value="'+row[0]+'"></div>';
}
},
],
dom: '<"datatable-scroll"t><"datatable-footer"ip>',
language: {
search: '<span>Filter:</span> _INPUT_',
searchPlaceholder: 'Type to search...',
lengthMenu: '<span>Show:</span> _MENU_',
paginate: { 'first': 'First', 'last': 'Last', 'next': $('html').attr('dir') == 'rtl' ? '←' : '→', 'previous': $('html').attr('dir') == 'rtl' ? '→' : '←' }
}
});
And Update function is like below
var positionArray = [];
oInnerTable.on( 'row-reorder', function ( e, diff, edit ) {
for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
var rowData = oInnerTable.row( diff[i].node ).data();
positionArray.push({
myid:rowData[0],
mypositiion: diff[i].newData
});
}
if (positionArray.length>0) {
$.post("/link-to-script.php", {
positionArray: positionArray
}, function(data, status) {
positionArray = [];
})
} ;
} );
Since I have three rows in table, everytime when I change position, its calling ajax three time and sometime its even more time, Its not possible that its fire only one time and I can send position data to server with single ajax call?
Thanks!
I am trying to fetch data from an API of WordPress.
Here is my code:
column.data().unique().sort().each(function (d,j) {
var practiceArea = d.practice_area;
var jsonPacticeArea = JSON.stringify(practiceArea);
if (jsonPacticeArea !== undefined) {
var res = $.map(jsonPacticeArea.split("|"), $.trim);
for (var i = 0; i < res.length; i++) {
var str = res[i];
str = str.replace(/"/gi, '').trim();
if (arrayPracticeArea.indexOf(str) === -1) {
arrayPracticeArea.push(str);
}
}
}
});
the "column" is the variable that is getting data through an API, and as far as I do console.log(column. data().unique().sort()), that's returning complete data as you can see in the screenshot and I want to fetch data is marked in red rectangle and store those values in an array, but as soon as I try to add "each" function to fetch the data and store it in an array (in my case its arrayPracticeArea) its returning undefined values.
Can anyone please help me out? I am just not much experienced with Javascript API.
Here is my AJAX code:
var tableAttorney = $('#table_affliate_attorney').DataTable({
destroy: true,
searching: true,
bLengthChange: false,
scrollX: true,
scrollY: 440,
autoWidth: false,
"language": {
"emptyTable": "We are sorry but there are no Affiliate Attorneys within a 150 mile radius of your requested search"
},
ajax: {
type: 'get',
url: "/wp-admin/admin-ajax.php",
dataType: 'json',
cache: false,
data: {
'action': 'get_attorney_ajax',
'center_lat': center_lat,
'center_long': center_long,
'state': state,
'city': city,
'zip': zip
}
},
columns: [
{"data": "title"},
{"data": "city"},
{"data": "state"},
{"data": "zip"},
{"data": "distance"},
{
"data": "phone",
className: 'datatablePhone',
render: function (data) {
return '' + data + '';
}
},
{
"data": "email",
className: 'px190EM',
render: function (data) {
return '' + data + '';
}
},
{
className: 'js-practice-area',
"data": "practice_area"
},
{
"targets": -1,
"data": 'email',
render: function (data) {
return "<a class='contact-lawyer' href='#' data-toggle='modal' data-target='#exampleModal' data-whatever='#mdo' data-email='"+data+"'>Contact</a>";
}
},
],
columnDefs: [
{"width": "150px", "targets": [0]},
{"width": "130px", "targets": [5]}
],
So I am trying to fetch data from columns->data that has value practice_area
I want to create and show number sort ascending data in datatables like in this picture
index number
and I don't have sorted data number in database and my json data
this is my code:
$(document).ready(function() {
$('#dataya').DataTable({
lengthChange: false,
ajax: {
url: "http://localhost/jdih_webservice/api/xxxx",
dataSrc: ""
},
columns: [
{ data: "id_dokumen"},
{ data: "judul"},
{ data: "subjek"}
],
select: true
});
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
var myTable = $('#dataya').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"bDestroy": true,
"autoWidth": true,
"data": [],
"columns": [{
"title": "ID",
"data": "id_dokumen"
}, {
"title": "Judul",
"data": "judul"
}, {
"title": "Subjek",
"data": "subjek"
}],
"order": [[ 1, 'asc' ]]
});
if(start_date != '' && end_date !='')
{
var startDate = new Date(start_date);
var tglmulai = startDate.getFullYear();
var endDate = new Date(end_date);
var tglselesai = endDate.getFullYear();
let url = 'http://localhost/jdih_webservice/api/xxxx';
fetch(url)
.then(res => res.json())
.then((out) => {
var resultProductData = out.filter(function(a) {
var createdAt = new Date(a.tgltetap);
var tgldata = createdAt.getFullYear();
if( tgldata >= tglmulai && tgldata <= tglselesai ) return a;
});
myTable.clear();
$.each(resultProductData, function (index, value) {
myTable.row.add(value);
});
myTable.draw();
})
.catch(err => { throw err });
}
});
});
Anyone could help? , so appreciate thanks
and maybe if you not busy could you create/build in jsfiddle
This code is from this DataTables thread and should do what you want. It's using an additional column for the indexes:
dataTable.on( 'order.dt search.dt', function () {
dataTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
I have created a jquery grid and loaded the json data into it.. And i have some radiobuttons on pop up.. based on that selection the json value is changed. For the first time , the json is loaded into gqgrid. but when i select other radio button the json value is changed but that new json is not loaded into jqgrid. The old json is showing.
I have tried ,
obj.datatype = "local";
obj.viewrecords = true;
obj.rowNum = 20;
obj.pager = "#jqGridPager";
obj.data = jsonValue;
obj.localReader = {repeatitems: true};
obj.rowList = [20,30,50];
obj.loadonce = true;
obj.colModel = [
{ "label": 'Id', "name": 'studentId', "width": "150" , "key" : true},
{ "label": 'No', "name": 'studentNo', "width": "150"},
{ "label": 'Name', "name": 'studentName', "width": "150"},
{ "label": 'Phone', "name": 'studentPhone', "width": "150"},
{ "label":'Email', "name": 'primaryContactEmail', "width": "150" },
{ "label":'Address', "name": 'studentAddress', "width": "150" }
];
obj.multiselect = true;
obj.navOptions = { reloadGridOptions: { fromServer: true } };
//console.log(obj)
$("#grid_json").jqGrid(obj).jqGrid('filterToolbar').navGrid('#jqGridPager',
{ edit: false, add: false, del: false, search: true, refresh: true, view: true, position: "left", cloneToTop: true },
{
editCaption: "The Edit Dialog",
recreateForm: true,
checkOnUpdate : true,
checkOnSubmit : true,
closeAfterEdit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
closeAfterAdd: true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
{
multipleSearch: true
}
)
// add first custom button
/* $('#grid_json').navButtonAdd('#jqGridPager',
{
buttonicon: "ui-icon-mail-closed",
title: "Send Mail",
caption: "Send Mail",
position: "last",
// onClickButton: customButtonClicked
}); */
/// add second custom button
$('#grid_json').navButtonAdd('#jqGridPager',
{
buttonicon: "ui-icon-pencil",
title: "Edit",
caption: "Edit",
position: "last",
//onClickButton: customButtonClicked
});
Try this first clear the grid data then reset the data property of the grid options to your new json data.
var grid = $("#grid_json");
grid.jqGrid('clearGridData').jqGrid('setGridParam', {
data: new_data
}).trigger('reloadGrid', [{ page: 1 }]);
I'm working with Kendo UI's Grid and attempting to add some code which preserves the grid's filter/grouping/etc by way of a cookie. It works in the example, but not at all in my code.
Example: http://www.kendoui.com/code-library/web/grid/preserve-grid-state-in-a-cookie.aspx
My Code: http://jsfiddle.net/PwajE/
For whatever reason (I'm sure it's a simple one) I keep getting type errors. Two hours later... here I am.
As always, any help is appreciated.
#RRfive
<script>
var data = [{"name":"John Smith","email":"test#test.com","permission":"admin","costRate":"60","dt":"2013-02-02 10:26:29","memberID":"M0000001"},{"name":"Test Simple","email":"test#jones.com","permission":"user","costRate":"40","dt":"2013-02-02 00:00:00","memberID":"M0000002"}];
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
data: data,
//transport: {
// read: "assets/data/data.users.php",
//},
schema: {
data: function(result) {
return result.data || result;
},
total: function(result) {
var data = this.data(result);
return data ? data.length : 0;
},
model:{
id:"memberID",
fields:{
dt:{ type:"date" },
costRate:{ type:"number" }
}
}
},
pageSize: 10,
},
sortable: {
mode: "single",
allowUnsort: true,
},
pageable: {
input: true,
numeric: false
},
reorderable: true,
resizable: true,
filterable: {
extra:false,
operators: {
string:{
contains: "Contains",
}
}
},
columnMenu: false,
groupable: true,
dataBound: function(e){
var grid = this;
var dataSource = this.dataSource;
var state = kendo.stringify({
page: dataSource.page(),
pageSize: dataSource.pageSize(),
sort: dataSource.sort(),
group: dataSource.group(),
filter: dataSource.filter()
});
$.cookie("employeesState",state);
if($.cookie('empRows')){
$.each(JSON.parse($.cookie('empRows')),function(){
var item = dataSource.get(this);
var row = grid.tbody.find('[data-uid='+item.uid+']');
row.addClass('k-state-selected');
})
}
},
change:function(){
var grid = this;
var ids = grid.select().map(function(){
return grid.dataItem($(this)).Id
}).toArray();
$.cookie('empRows',JSON.stringify(ids));
},
columns: [
{ field: "name", title:"Name" },
{ field: "email", title:"Email/Username" },
{ field: "costRate", title:"Cost Rate (p/hr)", template: '#= kendo.toString(costRate, "c") #', },
{ field: "permission", title:"Permission", template: "#= (permission == 'admin') ? 'Administrator' : 'User' #" },
{ field: "dt", title:"Registered", template: '#= kendo.toString(dt,"d-M-yyyy") #' },
{ field: "memberID", title:" ", width: "83px", filterable: false, sortable: false, template: '<a class="k-button k-button-icontext k-grid-edit" href="manage_admin.php?form=editMember&ID=#= kendo.toString(memberID, "n2")#"><span class=\"k-icon k-edit\"></span>Edit</a>'},
]
});
var state = JSON.parse($.cookie("employeesState"));
if(state){
if(state.filter){
parseFilterDates(state.filter, grid.dataSource.options.schema.model.fields);
}
grid.dataSource.query(state);
}
else{
grid.dataSource.read();
}
});
function parseFilterDates(filter, fields){
if(filter.filters){
for(var i = 0; i < filter.filters.length; i++){
parseFilterDates(filter.filters[i], fields);
}
}
else{
if(fields[filter.field].type == "date"){
filter.value = kendo.parseDate(filter.value);
}
}
}
</script>
If you debug that fiddle you would see that the following line throws the error:
grid.dataSource.query(state);
The reason for this is that grid is not an instance of Kendo Grid but the div elemen with id='grid'. The fix is simple - initialize the grid variable prior to using it:
var grid = $("#grid").data('kendoGrid');
grid.dataSource.query(state);