i have created a custom select field into my datatable
html = '<div class="col-md-3"><select id="filterleads" class="filterleads form-control">';
html += '<option value="all">All Leads</option>';
html += '<option value="processed">Processed Leads</option>';
html += '<option value="unprocessed">Unprocessed Leads</option>';
html += '</select></div>';
$("div.toolbar").html(html);
which looks like this
now when the select changes i want it to send its value with the datatable ajax so i can filter records according to that
this is how im doing this
var table = $('#allleadstable').DataTable( {
"processing": true,
"serverSide": true,
"responsive": true,
"iDisplayLength": 50,
"sScrollX": "100%",
"order": [[ 1, "desc" ]],
"sScrollXInner": "100%",
"bScrollCollapse": true,
"ajax": {
url:"/leads",
data: {
"leadfilter": ($("#filterleads").val() ? $("#filterleads").val() : 'all')
}
},
"scrollX":true,
"scrollCollapse": true,
//"sDom": '<"top"flip>rt<"bottom"flip><"clear">',
"dom": '<"toolbar">frtip',
columnDefs: [
{ width: 60, targets: 0 },
{ width: 50, targets: 1 },
{ width: 50, targets: 2 },
{ width: 150, targets: 3 },
{ width: 150, targets: 4 },
{ width: 100, targets: 5 },
//{ width: 100, targets: 7 },
{ width: 100, targets: 6 }
]
});
$(document).on("change", "#filterleads", function(event) {
table.ajax.reload();
});
The problem is that it doesn't find $("#filterleads") and always send the value 'all' even when i change the select
How do I send its value everytime I change select?
The issue is because you only read the value of your select when the page loads, and it's all by default. You need to change your code so that it reads the value of the select when it makes the request. To do this provide a function to the data property:
"ajax": {
url: "/leads",
data: function(data) {
data.leadfilter = $("#filterleads").val()
}
},
Note that I removed the ternary as it's not needed. The select will always have a value.
For more information see the ajax.data entry in the DataTables documentation.
For one dynamic field and 2 static its also may looks like:
ajax: {
url: '/action.php',
data: {
controller: 'someController',
action: 'someAction',
leadfilter: () => $('#filterleads').val()
}
},
Related
I am using Select2 JS and Datatables JS. The data is in JSON format. The data for one value should display as Animal & Veterinary. In JSON it appears as Animal \u0026amp; Veterinary. The Select2 filter displays it as Animal & Veterinary. How can I add a function to the JS below that will decode the Unicode? Below is a function that can work but I dont know how to add it to the JS below.
var title = 'Animal & Veterinary';
function stringToSlug (title) {
return title.toLowerCase().trim()
.replace(/&/g, 'and')
}
Below is the script. This is where I would like to pass the function into the filter. "select2config"
jQuery( document ).ready( function($) {
'use strict';
// Check condition first if the table class exists then run this init.
if ($('.lcds-datatable--advisory-committee-materials').length > 0) {
let pageClass = function () {
let el = $( 'ul.pagination' ).addClass('pagination-sm');
}
// define order of table's control element
let domStyling = "<'row'<'col-sm-12'lB>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>";
var otable9 = $('table.lcds-datatable--advisory-committee-materials').DataTable( {
// Sort of first date column descending.
order: [[0, 'desc']],
deferRender: true,
deferLoading: 50,
dom: domStyling,
ajax: {
"url": "/datatables-json/advisory-committee-materials-json",
//"url": "/sites/default/files/actest1.json",
"dataSrc": ""
},
processing: true,
columns: [
{ "data": "field_publish_date" }, // publish_date 0
{ "data": "title" }, // node title summary 1
{ "data": "field_site_structure" } // site_structure Committee/Topic 2
],
columnDefs: [
{
"type": "date",
"targets": [ 0 ]
}
],
pageLength: 10,
searching: true,
autoWidth: false,
responsive: true,
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
buttons: [
{
extend: 'excel',
text: 'Export Excel',
exportOptions: {
columns: [ 0, 1, 2 ]
}
}
],
initComplete: pageClass,
drawCallback: pageClass
}); // end datatable
// config and initialize filters
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
}
let search = $( '#lcds-datatable-filter--search' ).lcdsTableFilter({
table: otable9,
type: 'search'
});
let clear = $( '#lcds-datatable-filter--clear' ).lcdsTableFilter({
table: otable9,
type: 'clear'
});
// wait for ajax call to complete to load column data load
$('table.lcds-datatable--advisory-committee-materials').on( 'init.dt', function() {
let committee = $( '#lcds-datatable-filter--committee-topic' ).lcdsTableFilter({
column: 2,
table: otable9,
select2Options: select2config,
type: 'select',
dataType: 'datatable'
});
})
}}); // end ready function and condition if the table class exists.
I was able to pass in a function to alter the output of JSON so now the filter displays “Animal & Veterinary” not “Animal & Veterinary” By adding this below. The filter now displays Animal & Veterinary but selecting this in the filter does not match the value in the datatable?
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
escapeMarkup: function (text) { return text; }
}
var specificatonsData = [];
function initGridForTransactions(gridID, gridPagerID) {
var grid_selector = gridID;
var pager_selector = gridPagerID;
$(window).on('resize.jqGrid', function () {
$(grid_selector).jqGrid('setGridWidth', $("#page-wrapper").width());
})
var parent_column = $(grid_selector).closest('[class*="col-"]');
$(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
setTimeout(function () {
$(grid_selector).jqGrid('setGridWidth', parent_column.width());
}, 0);
}
})
$(grid_selector).jqGrid({
data: specificatonsData,
datatype: "local",
colNames: ['Id','Specification', 'Abbreviation'],
colModel: [
{ name: 'Id', width: 80,key:true },
{ name: 'specification', index: 'Id', key: true, width: 300 },
{ name: 'abbreviation', width: 300 },
],
cmTemplate: { editable: true },
cellsubmit: 'clientArray',
editurl: 'clientArray',
viewrecords: true,
rowNum: 4000,
gridview: true,
rowList: [4000],
pager: pager_selector,
altRows: true,
loadonce: true,
multiselect: false,
multiboxonly: false,
sortname: 'Specification',
sortorder: "asc",
cellEdit: false,
iconSet: "fontAwesome",
onSelectRow: function (rowId, status, e) {
var dealerFeatures = $("#editor").text();
var selectedFeature = rowId;
selectedFeature = selectedFeature.replace(/(\s+)/, "(<[^>]+>)*$1(<[^>]+>)*");
var pattern = new RegExp("(" + selectedFeature + ")", "gi");
dealerFeatures = dealerFeatures.replace(pattern, "<mark>$1</mark>");
//dealerFeatures = dealerFeatures.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/, "$1<mark>$2</mark>$4");
dealerFeatures = dealerFeatures.replace(/(<mark>[<>]*)((<[>]+>)+)([<>]*<\/mark>)/, "$1<mark>$2</mark>$4");
dealerFeatures = dealerFeatures.replace(/\n/g, '<br>\n');
$("#editor").html(dealerFeatures);
},
gridComplete: function () {
$(grid_selector).setColProp('Approve', { editoptions: { value: '' } });
},
loadComplete: function () {
var table = this;
setTimeout(function () {
updatePagerIcons(table);
enableTooltips(table);
}, 0);
},
}).navGrid(pager_selector, { edit: true, add: true, del: false },
{
url: '/Activity/SaveSpecification',
closeAfterAdd: true,
closeAfterEdit: true,
afterSubmit: function () {
getAbbrData();
return [true, '', ''];
}
});
jQuery(grid_selector).sortableRows();
function updatePagerIcons(table) {
var replacement =
{
'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
};
$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
var icon = $(this);
var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
})
}
function enableTooltips(table) {
$('.navtable .ui-pg-button').tooltip({ container: 'body' });
$(table).find('.ui-pg-div').tooltip({ container: 'body' });
}
$(document).one('ajaxloadstart.page', function (e) {
$(grid_selector).jqGrid('GridUnload');
$('.ui-jqdialog').remove();
});
}
I will save data to database only when I click on external Submit button.
When I click on edit button the data is showing in a popup and when I click on the save button the data is getting to the database and showing in the jqgrid.
But I have a new requirement where I have to show the data in the jqgrid when click on save button but should not save to the database.
Thanks in advance.
If you use Guriddo jqGrid JS then you can set url in edit options in your navigator to be clientArray - i.e
...navGrid(pager_selector, { edit: true, add: true, del: false },
{
url: 'clientArray',
closeAfterAdd: true,
closeAfterEdit: true,
afterSubmit: function () {
getAbbrData();
return [true, '', ''];
}
});
This will save the data locally.
The code, which you posted contains many small bugs. For example,
you use url: '/Activity/SaveSpecification' as form Edit options (not for Add form) - see navGrid call. You should remove the option to make editurl: 'clientArray' working
you use key:true in more as one column. It's not allowed. One can use it only in one column, which contains unique values.
the usage of index: 'Id' property in colModel for the column name: 'specification' is probably one more bug, which can make wrong sorting and filtering in the column.
your current code contains call of .setColProp('Approve', { ... });, which is wrong, because your colModel don't contains the column 'Approve'
the option sortname: 'Specification' is wrong too, because the value of sortname should be the value of name property from colModel (like sortname: 'specification' for example, if you'll remove index: 'Id' property from the column).
Additionally the usage of rowNum: 4000 can essentially reduce the performance of the grid in case of large grid. If real number of rows is about 4000, then it's much more effective to use local paging of data. The monitor allows to display only about 20-25 rows. Thus it's recommended to use pager with such small rowNum. Users can use paging buttons to go to the next page.
We are using the Scroller plugin for our jquery data table to allow virtual scrolling. However, we have requirement to support text wrapping inside a cell, as user would like to view the entire text instead of truncated one. I observed that it does not wrap the text by default. Is there a way to support this feature? Any possible workaround?
Fiddler
https://jsfiddle.net/Vimalan/2koex0bt/1/
html Code:
<table id="example" class="display" cellspacing="0" width="100%"></table>
js code:
var detailsSample = "DataTables and its extensions are extremely configurable libraries and almost every aspect of the enhancements they make to HTML tables can be customised. Features can be enabled, disabled or customised to meet your exact needs for your table implementations."
var dataList = [];
for (var i=1; i<=500; i++)
{
var dataRow = {};
dataRow.ID = i;
dataRow.FirstName = "First Name " + i;
dataRow.LastName = "Last Name " + i;
if (i%5 ==0)
{
dataRow.Details = detailsSample;
}
else
{
dataRow.Details = "Large text "+i;
}
dataRow.Country = "Country Name";
dataList.push(dataRow);
}
$('#example').DataTable( {
data: dataList,
deferRender: true,
scrollX: true,
scrollY: 200,
scrollCollapse: true,
scroller: true,
searching: false,
paging: true,
info: false,
columns: [
{ title: "ID", data: "ID" },
{ title: "First Name", data: "FirstName" },
{ title: "Change Summary", data: "LastName"},
{ title: "Details", data: "Details", "width": "400px" },
{ title: "Country", data: "Country" }
]
} );
Expectation
In the above table, the "Details" column should always have a width of 400px and the text in that column should wrap.
Any suggestion will be greatly appreciated.
Found the solution by wrapping the column data in a div and setting the white-space, width css properties for the div.
Fiddler:https://jsfiddle.net/Vimalan/2koex0bt/6/
JS
$('#example').DataTable( {
data: dataList,
deferRender: true,
scrollX: true,
scrollY: 200,
scrollCollapse: true,
scroller: true,
searching: false,
paging: true,
info: false,
columns: [
{ title: "ID", data: "ID" },
{ title: "First Name", data: "FirstName" },
{ title: "Change Summary", data: "LastName"},
{ title: "Details", data: "Details" },
{ title: "Country", data: "Country" }
],
columnDefs: [
{
render: function (data, type, full, meta) {
return "<div class='text-wrap width-200'>" + data + "</div>";
},
targets: 3
}
]
} );
CSS
.text-wrap{
white-space:normal;
}
.width-200{
width:200px;
}
Not sure if you add in stylesheets or not, but set your table-layout to fixed and add in the white-space. Currently you are using white-space:no-wrap which negates what you're trying to do. Also I set a max-width to all your td's so this will happen whenever there is overflow.
Add this at the end of your jQUery
https://jsfiddle.net/2koex0bt/5/
$(document).ready(function(){
$('#example').DataTable();
$('#example td').css('white-space','initial');
});
If you want to just use the api, do this ( add in anymore CSS to change the styling ).
If you want to do it with CSS, do this:
table {
table-layout:fixed;
}
table td {
word-wrap: break-word;
max-width: 400px;
}
#example td {
white-space:inherit;
}
Js Code:
'columnDefs': [{
render: function (data, type, full, meta) {
let instaText = (data != null && data.length > 25) ? data.substr(0, 25) : data == null?"":data;
return '<div class="text-overflow" title='+'"'+ data +'"' +'>' + instaText + '</div>';
},
targets: [27]
}],
CSS:
{
overflow: hidden;
text-overflow: ellipsis;
max-width: 80%;
}
I'm trying to get my javascript to use a dynamic value for "displayStart". I'm getting the data from a php script that returns JSON.
Here is my js:
balance.list = function () {
$('#balance').dataTable({
processing: true,
ajax: {
url: 'php/list.php',
dataSrc: 'data'
},
dom: '<"top"flp<"clear">>rt<"bottom"ip<"clear">>',
pageLength: 50,
autoWidth: false,
displayStart: '100',
columns: [
{
width: "10%",
data: "date"
}, {
width: "5%",
data: "checknum"
}, {
width: "75%",
data: "description"
}, {
width: "5%",
data: "debit"
}, {
width: "5%",
data: "credit"
}, {
width: "5%",
data: "balance"
}]
});
};
instead of
displayStart: '100',
I want it be something like:
displayStart: displayStart.displayStart,
But I'm setting the dataSrc to data, which is another branch of the JSON
And here is the JSON data:
{
"displayStart":"100",
"data": [
{
"date":"2015-03-27",
"checknum":null,
"description":null,
"debit":"50.00",
"credit":"0.00",
"balance":"500.00"
},
{
"date":"2015-03-28",
"checknum":null,
"description":null,
"debit":"0.00",
"credit":"250.00",
"balance":"750.00"
}
]
}
I've messed around with the ajax portion using a success/error function, but then it doesn't continue on to finish the table.
How do I set the value?
You can change the page after the data has been loaded by adding two event handlers after you DataTables initialization code as shown below.
// Handles DataTables AJAX request completion event
$('#balance').on('xhr.dt', function( e, settings, json){
$(this).data('is-loaded', true);
});
// Handles DataTables table draw event
$('#balance').on('draw.dt', function (){
if($(this).data('is-loaded')){
$(this).data('is-loaded', false);
var api = $(this).DataTable();
var json = api.ajax.json();
var page_start = json['displayStart'];
// Calculate page number
var page = Math.min(Math.max(0, Math.round(page_start / api.page.len())), api.page.info().pages);
// Set page
api.page(page).draw(false);
}
});
I am using http://datatables.net/
The demo table on their homepage resembles pretty much the exact same thing that i'm using (pagination, specifically), except each row has an area to click:
<%= Post.title %>
This link opens a jquery UI modal dialog which displays some information which is ajax requested.
Part 1 (solved), see part 2 below
I'm trying to run an onclick event which works normally on page one, but as soon as i go to page 2 (or any others) it stops working. I checked the source to make sure it wasnt doing anything funny in all the code is infact there (all the rows, even the ones hidden by the pagination)
Any ideas?
$(function() {
$('#dialog').dialog({
autoOpen: false,
resizable: false,
maxHeight: 600,
width: 650,
modal: true,
beforeClose: function close() {
$('#dialog').html('');
}
});
$('.show-post').click(function() {
clickLink(this);
return false;
});
});
Thanks to those who answered my question! I fixed that issue.
Part 2
my next 'issue' id like to get to work is... I'm using the left and right arrow keys to allow them to 'scan' to the next or previous row, and display the information. This is as opposed to closing it and then having to click the next one.
I'd like to make it so when you get to the bottom of page one, or top of page two, hidding next/previous respectively will automatically load that page, go to the top (or bottom), then open that dialog for that row on the other page.
heres my click function (i know its kind of probably not structured the best... im new to jquery)
$(document).ready(function() {
oTable = $('#posts').dataTable({
"bJQueryUI": true,
"iDisplayLength": 400,
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"aLengthMenu": [[-1, 400, 100, 50], ["All", 400, 100, 50]]
});
$(this).keydown(function(e) {
var id = $("#dialog").attr("data-id");
currentPost = $("#posts tr[data-id=" + id + "]");
if (e.keyCode == 39 && $('#dialog').html() != "") {
/* Remove current background */
$(currentPost).blur()
$(currentPost).removeClass("current");
$(currentPost).find("td.sorting_1").removeClass("current");
var next = currentPost.next().find(".show-post");
clickLink(next);
} else if (e.keyCode == 37 && $('#dialog').html() != "") {
/* Remove current background */
$(currentPost).removeClass("current");
$(currentPost).find("td.sorting_1").removeClass("current");
var prev = currentPost.prev().find(".show-post");
clickLink(prev)
}
});
});
heres the actual click function
function clickLink(src) {
var post = $(src);
var id = $(post).parent().parent().attr('data-id');
/* Set background for current line */
$(post).parent().parent().find("td.sorting_1").addClass("current");
$(post).parent().parent().addClass("current");
$('#dialog').attr("data-id", id);
$('#dialog').load('/show-post/' + id, function() {
$.ajax({
type: "POST",
url: "/checkstatus/" + id,
dataType: "html",
error: function(data){
$("#dialog").fadeOut("fast", function() {
$("#dialog").html("<img src='/img/invalid.jpg' alt='invalid' style='margin: 40px auto; display: block;'>").fadeIn("slow");
});
}
});
/* Set Visited */
$(post).parent().parent().removeClass("visited").addClass("visited");
$('#dialog').dialog({
title: post.html(),
beforeClose: function close() {
$(post).parent().parent().find("td.sorting_1").removeClass("current");
$(post).parent().parent().removeClass("current");
},
buttons: {
"Email 1": function() {
$.ajax({
type: "POST",
url: "/get-email/" + id + "/" + "1",
dataType: "html",
success: function(data) {
window.location.href = data + "&subject=" + post.html();
}
});
},
}
});
$('#dialog').dialog('open');
});
return false;
};
The example on the link you provided appears to be adding/removing DOM elements, meaning that elements on subsequent pages probably are not in the DOM on page load. Have you tried using event delegation?
$(<root element>).delegate('.show-post', 'click', function() {
clickLink(this);
return false;
});
Where <root element> can be document but should be set to an ancestor element that is always in the DOM.
.delegate():
Attach a handler to one or more events for all elements that match the
selector, now or in the future, based on a specific set of root
elements.
Source: http://api.jquery.com/delegate
UPDATE
Note that .delegate() is an alias of .on() now, so if you're using jQuery 1.7+ I would just use .on() right from the get-go. Almost the same syntax except the selector and event are swapped: $(<root element>).on('click', '.show-post', function() { ... });
Source: Thanks Greg Pettit, Excellent Comment
Below Code is working Perfectly. When you click the pagination button 'drawCallback' class Call some function after table load.
$("#YourTableID").dataTable({
bJQueryUI: false,
bFilter: false,
bSearchable: false,
bInfo: false,
bAutoWidth: false,
bDestroy: true,
"oLanguage": {
"sEmptyTable": "No Records Found"
},
"sPaginationType": "full_numbers",
"bLengthChange": false,
"iDisplayLength": 5,
aaData: arrv,
aoColumns: [{
sTitle: "Select",
orderable: false,
className: 'select-checkbox',
targets: 0
},
{
sTitle: "Course name"
}, {
sTitle: "Level"
}, {
sTitle: "Study Mode"
}, {
sTitle: "Entry Year"
}, {
sTitle: "Point of Entry"
}, {
sTitle: "Awarding qualification"
}],
drawCallback: function () {
//Some function...
},
select: {
style: 'os',
background: 'color:gray',
selector: 'td:first-child'
},
order: [[1, 'asc']],
});
As #scrappedcola pointed out in the comments, your click handler is lost after pagination. There is a drawCallback function for DataTables you can implement which will fire after the table is "re-drawn" (hence drawCallback). Here is an example:
$('#someId').DataTable({
lengthMenu: [ 25, 50, 100, 200 ],
order: [[ 0, 'asc' ]],
processing: true,
serverSide: true,
stateSave: true,
responsive: true,
bDestroy: true,
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
],
drawCallback: function() {
var api = this.api();
api.$('#someBtnId').click(function() {
// do some click handler stuff
});
}
});