Enable/Disable Html button based on the data from the server - javascript

I am using datatable Jquery and making an ajax call to read data from the server.
Lets say database has 3 attributes "Attribute1 , Attribute2, Status".
Depending upon the Status, the third column on the datatable should be enabled or disabled button.
function test(server_url,table_id){
.ajax({url: server_url,dataType:"html",success: function(result){
var json_obj=JSON.parse(result);
var Columns="<thead><tr>";
var Fields=[],Tool_columns=[];
UserGroupFields=json_obj.columns;
for(i=0;i<json_obj.columns.length;i++){
Columns+="<th>"+json_obj.columns[i]+"</th>";
var field_dic={};
var tool_dic={};
field_dic["label"]=json_obj.columns[i];
field_dic["name"]=json_obj.columns[i];
Fields[i]=field_dic;
Tool_columns[i]=tool_dic;
}
tool_dic["targets"]=-1;
tool_dic["data"]="null";
tool_dic["defaultContent"]="<button this.disabled=true'>Yes</button>";
myTable=('#'+table_id).DataTable({
"order":[[0,"desc"]],
aaData:json_obj.data,
dom: 'T<"clear">lfrtip',
columns:Tool_columns,
tableTools: {
sRowSelect: 'single',
"sRowSelector": "td:not(:last-child)",
"aButtons": [ {
"sExtends": "editButton",
"sButtonText": "Edit",
"target": "#"+table_id
}]
},
"search": {
"regex": true,
"smart": false
}
});
Through above code I am able to add a button to each row read from the server . So how do I now enable or disable it based on the third atrribute of each record "Status".
Type of Data :
Object { columns: Array[3], data: Array[2] }
Data :
[{"column1":"1","Column2":"abc","Status":"Yes"},{"column1":"2","Column2":"xyz","Status":"No"}]
Any leads would be appreciated.
I am new to JQuery and JavaScripts
Thanks

Check the value of status in data and set the button in aaData accordingly.
Added one line in your code :
field_dic["button"]=(json_obj.columns[i]["status"]=="LIVE")?"Button Text":"Button Text";
for(i=0;i<json_obj.columns.length;i++){
Columns+="<th>"+json_obj.columns[i]+"</th>";
var field_dic={};
var tool_dic={};
field_dic["label"]=json_obj.columns[i];
field_dic["name"]=json_obj.columns[i];
field_dic["button"]=(json_obj.columns[i]["status"]=="LIVE")?"<button disabled='disabled'>Button Text</button>":"<button>Button Text</button>";
Fields[i]=field_dic;
Tool_columns[i]=tool_dic;
}
Loop to read "Status" value and set the value accordingly.
for(i=0;i<json_obj.data.length;i++){
if(json_obj.data[i]["Status"]=="Yes"){
json_obj.data[i]["Status"]="<button disabled='disabled'>Button Text</button>";
}
else{
json_obj.data[i]["Status"]="<button>Button Text</button>";
}
}

Related

how to destroy table and reinitialize same table with new updated data using Datatables Jquery plugin

I am using Datatables plugin and dynmically populating the table with the data returned from server. on different table draws the returned data has variable no of columns. On each table intilization the code is checking if there has been previous initializations and removes it before creating a new table with dynamic data, using this code:
if ( $.fn.dataTable.isDataTable( '#contracts_forecast' ) ) {
$('#contracts_forecast').DataTable().clear();
$('#contracts_forecast').DataTable().destroy();
$('#contracts_forecast tbody').empty();
$('#contracts_forecast thead').empty();
}
On the serverside I am manually editing the data and updating the database. When the database is updated with new data , I want to refresh the table so the change is reflected in the table. In order to do that I am using an POST SUBMIT event, which is triggered after the data is submitted to server and then call the function getDT(filter_product_code, filter_product_name) to update the table with new data
PROBLEM:
When the post submit event is triggered , it recalls the function getDT(filter_product_code, filter_product_name); and change is reflected. BUT THE NEW TABLE with UPDATED IS ADDED TO CURRENT TABLE WITHOUT THE OLD TABLE BEING DESTROYED Which leaves me with two same tables on screen
p.s I am assuming every time getDT() function is called it should check for if table is initialized and destroy it before creating a new one using the same
$(document).ready(function() {
$('#filter').click(function(){
var filter_product_code = $('#filter_product_code').val();
var filter_product_name = $('#filter_product_name').val();
if(filter_product_code == '' || filter_product_name == '')
{
alert('Select Both filter option');
}
var columns = [];
getDT(filter_product_code, filter_product_name);
function getDT(filter_product_code, filter_product_name) {
$.ajax({
serverSide: true,
type:'POST',
url: "/XXX/_fetch.php",
data: {filter_product_code: JSON.stringify(filter_product_code),
filter_product_name: JSON.stringify(filter_product_name)},
success: function (data) {
data = JSON.parse(data);
columnNames = Object.keys(data.data[0]);
for (var i in columnNames) {
columns.push({data: columnNames[i],
title: capitalizeFirstLetter(columnNames[i])});
}
if ( $.fn.dataTable.isDataTable( '#contracts_forecast' ) ) {
$('#contracts_forecast').DataTable().clear();
$('#contracts_forecast').DataTable().destroy();
$('#contracts_forecast tbody').empty();
$('#contracts_forecast thead').empty();
}
table = $('#contracts_forecast').DataTable({
data: data.data,
columns: columns,
dom: "Bfrtip",
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
],
"columnDefs": [
{
"targets": [0],
"visible": false,
"searchable": false
},
{ className: "tablecolumns", targets: "_all" },
]
} );
$('#contracts_forecast').on( 'click', 'tbody td:not(:first-child)', function (e) {
editor.inline( this );
} );
}
});
editor.on( 'postSubmit', function ( e, json, data, action, xhr ) {
getDT(filter_product_code, filter_product_name);
});
}
});
} );
I was doing a mistake by declaring the column variable outside function. Each time the function was called it was adding to already existing columns. So just needed to define column variable inside function.
getDT(filter_product_code, filter_product_name);
function getDT(filter_product_code, filter_product_name) {
var columns = [];
$.ajax({
serverSide: true,
// paging: true,
// retrieve:true,
type:'POST',

How to update model data when using jQuery Data table with ASP.NET MVC

I have large amount of data returning from JSON and to sort,filter and page, I am using jQuery dataTable.
This is working perfect with sorting, searching and pagination.
But I have an issue when I am trying to bind model with View controls.
For example, I have following JSON returned,
{
"data":
[
{"IsSelected":true,"Name":"SMyDataPoint__01"},
{"IsSelected":true,"Name":"SMyDataPoint__04"},
{"IsSelected":true,"Name":"SMyDataPoint__07"},
{"IsSelected":true,"Name":"SMyDataPoint__08"},
{"IsSelected":true,"Name":"SMyDataPoint__09"},
{"IsSelected":true,"Name":"SMyDataPoint__10"},
{"IsSelected":true,"Name":"SMyDataPoint__11"}
]
}
And now I am using jQuery to populate the json data in my browser,
$('#myTableName').DataTable(
{
"ajax": {
"url": "/API/Loaddata",
"type": "GET",
"datatype": "json"
},
"columns": [
{
"data": "IsSelected",
"render": function (data, type, row) {
if (type === 'display') {
return '<input type="checkbox" class="editor-active">';
}
return data;
},
"className": "dt-body-center"
// "autoWidth": true
},
{ "data": "Name", "autoWidth": true }
],
"rowCallback": function (row, data) {
// Set the checked state of the checkbox in the table
$('input.editor-active', row).prop('checked', data.active == 1);
}
}
);
Though I am getting ISelected as true from JSON, in UI , they are not ticked.
The json objects you have shown do not have a property named active (and therefore data.active would return undefined). Use the IsSelected to set the checkedproperty.
$('#myTableName').DataTable({
....
"rowCallback": function (row, data) {
// Set the checked state of the checkbox in the table
$('input.editor-active', row).prop('checked', data.IsSelected);
}
})

Is there a way to pull from multiple SQL tables for one DataTables table?

I use DataTables to present data in a reporting website that I created. I am working on creating a Report Builder where users can select multiple tables and then columns from those tables for a custom report.
What I want to know is whether there's a way to do this with DataTables. I'm able to get the tables names and column names for the custom report, but I've not been able to figure out how to send it to DataTables. I currently use server side processing and send an ajax call using POST to the DataTable.
I know that I can program in a SQL query based on the selected tables and columns, but I cannot seem to figure out how to have the data sent to DataTables.
Here is how I initialize my DataTables:
$(document).ready(function ()
{
// Setup - add a text input to each footer cell
$('#DataTable tfoot th').each(function () //creates the search bar as the footer
{
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
var table = $('#DataTable').DataTable({
"lengthMenu": [[25, 50, 75, 100, 150, -1], [25, 50, 75, 100, 150, 'All']],
"dom": '<"top"Bifpl<"clear">>rt<"bottom"ip<"clear">>',
"buttons": [{
extend: 'collection',
text: 'Export',
buttons: ['export', { extend: 'csv',
text: 'Export All To CSV', //Export all to CSV file
action: function (e, dt, node, config)
{
window.location.href = './ServerSide.php?ExportToCSV=Yes';
}
}, 'csv', 'pdf', { extend: 'excel',
text: 'Export Current Page', //Export to Excel only the current page and highlight the first row as headers
exportOptions: {
modifier: {
page: 'current'
}
},
customize: function (xlsx)
{
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$('row:first c', sheet).attr('s', '7');
}
}]
}
],
"fixedHeader": { //Keeps the header and footer visiable at all times
header: true,
footer: true
},
"select": true, //sets the ability to select rows
"processing": true, //shows the "Processing" when working
"serverSide": true, //sends data to the server for processing
"ajax": { //where the data is sent and processed
"url": "./ServerSide.php",
"type": "POST"
},
stateSave: true, //Saves the current state of the page
columnDefs: [{ visible: false, targets: 0}], //Hides the first column the ID column
initComplete: function () //sets the search
{
var api = this.api();
// Apply the search
api.columns().every(function ()
{
var that = this;
$('input', this.footer()).on('keyup change', function (e)
{
if (that.search() !== this.value & e.keyCode == 13) //you have to hit enter for the search to start
{
that
.search(this.value)
.draw();
}
});
});
}
});
});
$.fn.dataTable.ext.buttons.export =
{
className: 'buttons-alert', //Adds the "Export all to Excel" button
id: 'ExportButton',
text: "Export All To Excel",
action: function (e, dt, node, config)
{
window.location.href = './ServerSide.php?ExportToExcel=Yes';
}
};
Here is what I can currently get to work:
I'm not sure else anyone would need to help me with this, but if I'm missing something let me know and I'll add it.
I need all the data from all selected tables and columns to be in one DataTables table presented on the website. In the image above I'm showing that I've gotten as far as getting the column headers and using aliases for the tables. I'm working through my FilterSort.class.pph file (which is like the ssp.class.php in DataTables) to see if I can get it to present the table.
I figured it out. I was still calling the correct DataTables functions, but I wasn't passing the data to the functions. I ended up having to update my ServerSide.php file and my FilterSort.class.php file. Those are the ones that all of the other reports use to send data from the server to the screen. After some trial and error, I got it to work and didn't need to change anything in the code posted in my question.

how to append json array in datatable using render function

I want to append json array into one popover attribute called data-content.
I am using jQuery DataTables plugin to perform UI functionalities. Using data variable table is populated with the data.
How could I insert titleDescription array from data variable into the attribute name called as data-content inside a tag in js , check my fiddle and go to datatable function there inside columnDefs there is render function. In that function I have return and append a tag, there only I have to append titleDescription array.
Check this JSFiddle for demonstration.
You can use the row attribute, and have the data in a non visible column.
Check the example
https://datatables.net/examples/advanced_init/column_render.html
$(document).ready(function() {
$('#example').DataTable( {
"columnDefs": [
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
return data +' ('+ row[3]+')';
},
"targets": 0
},
{ "visible": false, "targets": [ 3 ] }
]
} );
} );
That would do the trick.
You just need to add another column at the last of each row then you can access it from row like this
render : function(data, type, row) {
return '<span class="favlist-icon"></span><span class="immediate-attention-icon"> </span> <span class="docx-name-list-link"> <a class="apopoverdata" href="#" data-content="'+row[4]+'" rel="popover" >'+data+'</a></span>';
}
Here is working fiddle
https://jsfiddle.net/2cn4b8bz/4/
I'm not sure what library you were using for your pop over so I used tooltipster seeing as you had jQuery already for the DataTable. Your data didn't have everything you needed either so I've altered it a wee bit:
$(function() {
$('#documentListing-data').DataTable({
data: json.documentAll.document,
pageLength: 10,
columns:[
{
"data": "documentTitle",
"title": "Name",
"render": (data, type, row) => '' + data + '',
},
{
"data": "category",
"title":"Category",
"render": (data, type, row) => data.map((k, v) => k.trim()).join(", "),
},
{
"data": "publishedDate",
"title":"Published Date"
},
{
"data": "lastUpdatedDate",
"title": "Last Updated Date"
},
],
"drawCallback": function(settings) {
$('.tooltip').tooltipster();
}
});
});
Working JSFiddle. Hope that helps!

Datatables update single column every 5 seconds

I'm using datatables to show several information and button.
This is the javascript used to initialize the datatables
if ( ! $.fn.DataTable.isDataTable( '#datatableTable' ) ) {
datatableTable = $('#datatableTable').DataTable({
responsive: true,
columnDefs: [
{ "width": "25%", "targets": 4},
{
targets: [4,5,6],
//set priority to column, so when resize the browser window this botton stay on the screen because have max priority
visible: (document.getElementById('role').value == '[ROLE_ADMIN]' || document.getElementById('role').value == '[ROLE_FLEET_ENG]'
|| document.getElementById('role').value == '[ROLE_SUPPLIER]'),
responsivePriority: 1,
orderable: false,
searchable: false,
},
...
],
//fix problem with responsive table
"autoWidth": false,
"ajax":{
"url": "datatable/" + $("#selectedCar").val(),
"dataSrc": ...
return json.result.data;
},
"error": function (xhr, error, thrown) {
window.location.href = "/DART/500";
}
},
"columns": [
....
{data:null, render: function ( data, type, row ) {
var datId="deleteDat"+row.idAcquisition;
if (row.datUploaded){
return '<button type="button" class="btn btn-danger" name="deleteDat" target="'+row.idAcquisition+'" id="'+datId+'" data-toggle="modal"'
+'data-target="#deleteDatModal">Delete</button>'
}else
return '<button type="button" class="btn btn-danger" name="deleteDat" target="'+row.idAcquisition+'" id="'+datId+'" data-toggle="modal"'
+'data-target="#deleteDatModal" disabled>Delete</button>'
},
],
"fnDrawCallback": function(data, type, row, meta ) {
//Initialize checkbox for enable/disable user
$("[name='my-checkbox']").bootstrapSwitch({size: "small", onColor:"success", offColor:"danger"});
},
});
}
else {
datatableTable.ajax.url("datatable/" + $("#selectedCar").val()).load();
}
Column 5 (starting from 0) has buttons, each button may be disabled or enabled depends on the datUploaded boolean value.
This variable change if user load file ,but this value has setted after async task, so I don't know in my javascript when this task end.
I thought to update every 5 seconds only this column, but how can I do it?
I find datatableTable.column(5).cells().invalidate().render() but I receive an error (unknow parameter "isShow" for row 0) and update doesn't work.
Can you help me? Thanks
As I said in a comment, you can pass .load() a callback function that will be called automatically when the ajax request is complete. In this callback you can update your table as you prefer. After you update the table, remember to call datatableTable.draw(); to apply the changes.
I don't think invalidate() and render() are necessary.
So your else branch would be something like
datatableTable.ajax.url("datatable/" + $("#selectedCar").val()).load(function() {
/*
...do something to the table...
*/
datatableTable.draw();
});

Categories

Resources