eventHandler trigger multiple times when using .on() only - javascript

function changeStatus() {
$('#dataTable tbody').on('change', '.orderStatus', function () {..code}
}
function showOrdersInModal() {
$('#dataTable tbody').on('click', '.fa-eye-btn', function (e) {...code}
}
function addUrl() {
$('#dataTable tbody').on('click', '.addUrl', function () {..code}
}
function showOrders() {
$.ajax({
type: 'method',
url: 'url',
data: { data },
success: function (response) {
$('#dataTable').DataTable().clear().destroy();
let data = JSON.parse('[' + response.replace(/}{/g, '},{') + ']');
$('#dataTable').DataTable( {
autoWidth: false,
pageLength: 25,
lengthMenu: [[25, 50, 100, 500, -1], [25, 50, 100, 500, 'All']],
data: data,
columns: [
{ data: 'receipt' },
{ data: 'first_last_name' },
{ data: 'contact_no' },
{ data: 'address' },
{ data: 'email' },
{ data: 'url' },
{ data: 'status' },
],
});
showOrdersInModal();
changeStatus();
addUrl();
},
});
}
showOrders();
When I use .off() before .on(), the only last function will execute which is addUrl(); but when I remove the .off() it will trigger the event depending on how many times I click any of each button or element.
Is there a way that I can make the eventHandler trigger once even if I clicked any of the buttons multiple times?
or is there a way to execute all three functions not just the addUrl(); function at the end?

I found the answer and when using the dataTables I cannot access the DOM after the next page so I use drawCallback which like this:
$('#dataTable').dataTable({
drawCallback: function () {
showOrdersInModal();
changeStatus();
addUrl();
},
retrieve: true,
deferRender: true,
data: data,
columns: [
{ data: 'data' },
],
});
then I just use this.
$('.className').off().on('click', function () {..code}

Related

Hide a button in jquery based on user access

I'm trying to hide a button. If it was on the html i would simply do
<security:authorize access="hasAuthority('Administrator')">
//html button code
</security:authorize>
but my delete button is being generated from datatable.
var table = $('#dataTable').DataTable({
language: {
searchPlaceholder: "Search...",
emptyTable: "There are no available flows."
},
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
},
{type: "date-euro", targets: 7},
{type: "date-euro", targets: 8}
],
order: [[1, 'desc']],
select: {
style: 'multi',
selector: 'td:first-child'
},
lengthChange: false,
dom: 'Bfrtip',
buttons: [
{
text: '<span class="fa fa-plus"></span> Create',
className: 'btn-primary-outline',
action: function () {
location.href = "create-flow";
}
},
{
text: '<span class="fa fa-trash"></span> Delete',
className: 'btn-danger-outline',
action: function () {
console.log($('#hasAuthority').val());
var selectedRows = table.rows({selected: true});
if (selectedRows.nodes().length > 0) {
//Get names
var data = selectedRows.data();
var names = [];
$.each(data, function (index, value) {
names.push(value[2]);
});
//Remove them
$.ajax({
url: '/flow/delete?names=' + names,
type: 'delete',
success: function () {
//reload page
location.reload();
}
});
//de-select selected rows
table.rows('.selected').deselect();
}
}
}
]
});
I'm trying to give a value to a input if user is admin or not but I'm getting undefined
<security:authorize access="hasAuthority('Administrator')" var="hasAuthority"></security:authorize>
<input type="hidden" id="hasAuthority" value="${hasAuthority}">
But then how do I corporate the if(hasAuthority) only on the delete button? The syntax doesn't match.

DataTables API row().data()

Hi everybody and happy new year :)
So, I use dataTables library. In their web site i found this example, where function must return the row of table, which was clicked.
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
console.log( table.row( this ).data() );
} );
I try use this example for my code, but i have the error
Uncaught TypeError: aucTable.row is not a function
my code:
var mainTable = $('#mainTable');
$(document).ready(function () {
mainTable.dataTable({
'searching': false,
'ajax': 'assets/static_data/data.json',
'columns': [
{
title: "Name",
data: "name"
},
{
title: "Office",
data: "office"
},
{
title: "Extn.",
data: "extn"
},
{
title: "Salary",
data: "salary"
},
{
title: "Start date",
data: "start_date"
},
{
title: "Details",
data: null,
defaultContent: "<button class='details-btn btn'>More details</button>",
sorting: false
}
]
});
});
$('#mainTable').on('click', '.details-btn', function () {
var selectedRow = aucTable.row(this).data();
console.log(selectedRow);
$("<div id='details-dialog'/>").dialog({
modal: true,
show: true,
maxWidth: 620,
maxHeight: 300,
minWidth: 500,
minHeight: 200,
title: "Hello World"
});
});
Can somebody tell me, why I have this error? And why i can't get the row, which was clicked?
Tanks for everybody.
Best regard and have fun.
I'm not familiar with datatables, however you might try changing it to the following:
var mainTable = null;
$(document).ready(function () {
mainTable = $('#mainTable').dataTable({...});
});
$('#mainTable').on('click', '.details-btn', function () {
var tr = $(this).closest('tr');
var selectedRow = mainTable.row(tr).data();
console.log(selectedRow);
//...
});
Note that I'm storing the result to the $('#mainTable').dataTable() call in the mainTable variable so that you can reference it later when calling the row() function.
The other thing to note is that in your click handler, it looks like you need to find the tr from the datatable - calling mainTable.row(this) does not yield a row because this is the button that was clicked, not the row of the table.
See this link for an example that seems similar to what you're doing.
In the current code, the acuTable var not exist. So you can change your code in order to have an acuTable var pointing to the datatable instance, something like:
var mainTable = $('#mainTable');
var acuTable;
$(document).ready(function () {
acuTable = mainTable.dataTable({
'searching': false,
'ajax': 'assets/static_data/data.json',
'columns': [
{
title: "Name",
data: "name"
},
{
title: "Office",
data: "office"
},
{
title: "Extn.",
data: "extn"
},
{
title: "Salary",
data: "salary"
},
{
title: "Start date",
data: "start_date"
},
{
title: "Details",
data: null,
defaultContent: "<button class='details-btn btn'>More details</button>",
sorting: false
}
]
});
});
$('#mainTable').on('click', '.details-btn', function () {
var selectedRow = aucTable.row(this).data();
console.log(selectedRow);
$("<div id='details-dialog'/>").dialog({
modal: true,
show: true,
maxWidth: 620,
maxHeight: 300,
minWidth: 500,
minHeight: 200,
title: "Hello World"
});
});

DataTables Dynamic displayStart

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);
}
});

Dynatree is stuck loading the icon

I use dynatree to display a list of documents. When I load the template, the dynatree was stuck in the loading icon. What could be wrong?
$("#tree").dynatree({
checkbox: true,
selectMode: 2,
initAjax: {
url: "/getTree/",
dataType: "json",
data: {}
},
onSelect: function(node) {
},
onActivate: function (node) {
},
persist: true,
noLink: false,
fx: { height: "toggle", duration: 200 },
onPostInit: function (isReloading, isError) {
if (getStringOfSelectedTreeNodes() != '') {
}
}
}); });
</script>
Did you have an example maybe on CodePen to check what the issue is. It seems the last }); end braces was not needed, was this because it was within a jQuery $(document).ready(); method. Otherwise this would be the correct code: Some good examples on the dynatree example page which I'm sure you've seen.
$("#tree").dynatree({
checkbox: true,
selectMode: 2,
initAjax: {
url: "/getTree/",
dataType: "json",
data: {}
},
onSelect: function(node) {
},
onActivate: function (node) {
},
persist: true,
noLink: false,
fx: { height: "toggle", duration: 200 },
onPostInit: function (isReloading, isError) {
if (getStringOfSelectedTreeNodes() != '') {
}
}
});

Passing xhr data to rubaxa fileapi

I am using this api for file upload and need to pass some data dynamically when onFilePrepare event is fired but it is not sending that data to url. Please suggest as I have to add 1 new data param b from onFilePrepare event, which is not avaiable during initially since fileapi is being called from nested ajax setup
https://github.com/RubaXa/jquery.fileapi
CODE :
$('#multiupload').fileapi({
url: "url",
data: ({'a':'A'}),
clearOnComplete: true,
multiple: true,
elements: {
ctrl: { upload: '.js-upload' },
emptyQueue: { hide: '.js-upload' },
list: '.js-files',
name: '.js-name',
size: '.js-size',
file: {
tpl: '.js-file-tpl',
preview: {
el: '.b-thumb__preview',
width: 80,
height: 80
},
upload: { show: '.progress', hide: '.b-thumb__rotate' },
complete: { hide: '.progress' },
progress: '.progress .bar'
}
},
onFilePrepare : function(evt,ui) {
//pass more data dynamically
ui.xhr.options.data = { 'a':'A','b':'B'};
console.log(ui.xhr.options);
},
onComplete : function (evt, ui) {
//read ajax data returned
var data = JSON.parse(ui.xhr.response);
console.log(ui.xhr.options);
}
});
With latest Rubaxa library, this works by doing as below -
Thanks to rubaXa for helping in git
Changes in onFilePrepare
$('#multiupload').fileapi({
url: "url",
data: ({'a':'A'}),
clearOnComplete: true,
multiple: true,
elements: {
ctrl: { upload: '.js-upload' },
emptyQueue: { hide: '.js-upload' },
list: '.js-files',
name: '.js-name',
size: '.js-size',
file: {
tpl: '.js-file-tpl',
preview: {
el: '.b-thumb__preview',
width: 80,
height: 80
},
upload: { show: '.progress', hide: '.b-thumb__rotate' },
complete: { hide: '.progress' },
progress: '.progress .bar'
}
},
onFilePrepare : function(evt,ui) {
//pass more data dynamically
ui.options.data.b = 'B';
},
onComplete : function (evt, ui) {
//read ajax data returned
var data = JSON.parse(ui.xhr.response);
console.log(ui.xhr.options);
}
});

Categories