I have a couple of drop downs that are populated from SharePoint using SPServices. This part works great. But then, I have a button that on click loads data from SharePoint and uses the dropdown texts as filter to fetch the data that will populate a table using the DataTables plugin. This part works only once; if I click the button again, nothing happens.
This is how I populate the dropdowns:
$(document).ready(function () {
var theYear; // Selected Year
var theRO; // Selected RO
//Fills the Dropdown lists (Year and RO)
$().SPServices({
operation: "GetListItems",
async: false,
listName: "{ListID}",
CAMLViewFields: "<ViewFields><FieldRef Name='Fiscal_x0020_Year' /><FieldRef Name='Regional_x0020_Office' /></ViewFields>",
completefunc: function (xData, Status) {
//Add Select Value option
$("#dropdown").prepend($('<option>', {
value: '',
text: 'Select Fiscal Year'
}));
$("#dropdownRO").prepend($('<option>', {
value: '',
text: 'Select Regional Office'
}));
//Fetching Data from SharePoint
$(xData.responseXML).SPFilterNode("z:row").each(function () {
var dropDown = "<option value='" + $(this).attr("ows_Fiscal_x0020_Year") + "'>" + $(this).attr("ows_Fiscal_x0020_Year") + "</option>";
var dropDownRO = "<option value='" + $(this).attr("ows_Regional_x0020_Office") + "'>" + $(this).attr("ows_Regional_x0020_Office") + "</option>";
$("#dropdown").append(dropDown);
$("#dropdownRO").append(dropDownRO);
/////////////Deletes duplicates from dropdown list////////////////
var usedNames = {};
$("#dropdown > option, #dropdownRO > option").each(function () {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
////Deletes repeated rows from table
var seen = {};
$('#myTable tr, #tasksUL li, .dropdown-menu li').each(function () {
var txt = $(this).text();
if (seen[txt]) $(this).remove();
else seen[txt] = true;
});
});
} //end of completeFunc
}); //end of SPServices
$('.myButton').on('click', function () {
run()
});
}); //End jQuery Function
This is the function I need to run every time I click on "myButton" after changing my selection in the dropdowns:
function run() {
theYear = $('#dropdown option:selected').text(); // Selected Year
theRO = $('#dropdownRO option:selected').text(); // Selected RO
var call = $.ajax({
url: "https://blah-blah-blah/_api/web/lists/getByTitle('Consolidated%20LC%20Report')/items()?$filter=Fiscal_x0020_Year%20eq%20'" + theYear + "' and Regional_x0020_Office eq '" + theRO + "'&$orderby=Id&$select=Id,Title,Fiscal_x0020_Year,Notices_x0020_Received,Declined_x0020_Participation,Selected_x0020_Field_x0020_Revie,Selected_x0020_File_x0020_Review,Pending,Pending_x0020_Previous_x0020_Yea,Controversial,GFP_x0020_Reviews,NAD_x0020_Appeals,Mediation_x0020_Cases,Monthly_x0020_Cost_x0020_Savings,Monthly_x0020_Expenditure,Regional_x0020_Office,Month_Number", //Works, filters added
type: "GET",
cache: false,
dataType: "json",
headers: {
Accept: "application/json;odata=verbose",
}
}); //End of ajax function///
call.done(function (data, textStatus, jqXHR) {
var oTable = $('#example').dataTable({
"aLengthMenu": [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
"iDisplayLength": -1, //Number of rows by default. -1 means All Records
"sPaginationType": "full_numbers",
"aaData": data.d.results,
"bJQueryUI": false,
"bProcessing": true,
"aoColumns": [{
"mData": "Id",
"bVisible": false
}, //Invisible column
{
"mData": "Title"
}, {
"mData": "Notices_x0020_Received"
}, {
"mData": "Declined_x0020_Participation"
}, {
"mData": "Selected_x0020_Field_x0020_Revie"
}, {
"mData": "Selected_x0020_File_x0020_Review"
}, {
"mData": "Pending"
}, {
"mData": "Pending_x0020_Previous_x0020_Yea"
}, {
"mData": "Controversial"
}, {
"mData": "GFP_x0020_Reviews"
}, {
"mData": "NAD_x0020_Appeals"
}, {
"mData": "Mediation_x0020_Cases"
}, {
"mData": "Monthly_x0020_Cost_x0020_Savings",
"fnRender": function (obj, val) {
return accounting.formatMoney(val);
}
}, {
"mData": "Monthly_x0020_Expenditure",
"fnRender": function (obj, val) {
return accounting.formatMoney(val);
}
}],
"bDeferRender": true,
"bRetrieve": true,
"bInfo": true,
"bAutoWidth": true,
"bDestroy": true,
"sDom": 'T&;"clear"&;frtip',
"oTableTools": {
"aButtons": ["xls"],
"sSwfPath": "../../Style Library/js/datatables/TableTools/media/swf/copy_csv_xls_pdf.swf",
},
"sSearch": "Filter",
"fnDrawCallback": function () {
//Add totals row
var Columns = $("#example > tbody").find("> tr:first > td").length;
$('#example tr:last').after('<tr><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td></tr>');
//Formating the Total row number to no decimals
$("#example tr:last td:not(:first,:last)").text(function (i) {
var t = 0;
$(this).parent().prevAll().find("td:nth-child(" + (i + 2) + ")").each(function () {
t += parseFloat($(this).text().replace(/[\$,]/g, '') * 1);
});
return parseInt(t * 100, 10) / 100;
});
//Format the monthly expenditure and savings to currency formatFormating the currency
var cell = new Array();
cell[0] = $('#example tr:last td:nth-child(12)').text();
cell[1] = $('#example tr:last td:nth-child(13)').text();
$('#example tr:last').find('td:nth-child(12)').html(accounting.formatMoney(cell[0]));
$('#example tr:last').find('td:nth-child(13)').html(accounting.formatMoney(cell[1]));
$('#example tr:last').find('td:last').hide();
} //hides extra td that was showing
}); //End of Datatable()
}); //End of call.done function
$('#theTableDiv').slideDown();
} //end of run() function
I'm not a programmer, I'm just trying to learn. I would appreciate any help. Thanks in advance
I would guess that you are replacing the part of the page where the button lives. (you really need to format your code more neatly for SO... use JSFiddle.net and their TidyUp button).
If that is the case you need to use a delegated event handler:
$(document).on('click', '.myButton', function () {
run()
});
This listens at a static ancestor of the desired node, then runs the selector when the event occurs, then it applies the function to any matching elements that caused the event.
document is the fallback parent if you don't have a convenient ancestor. Do not use 'body' for delegated events as it has odd behaviour.
Related
ı have a code like
$(document).ready(function ()
{
$('#tbl-contact thead th').each(function () {
var title = $(this).text();
$(this).html(title+' <input type="text" class="col-search-input" placeholder="Search ' + title + '" />');
});
var table = $('#tbl-contact').DataTable({
"scrollX": true,
"pagingType": "numbers",
"processing": true,
"serverSide": true,
"ajax": "server.php",
order: [[2, 'asc']],
columnDefs: [{
targets: "_all",
orderable: false
}]
});
table.columns().every(function () {
var table = this;
$('input', this.header()).on('keyup change', function () {
if (table.search() !== this.value) {
table.search(this.value).draw();
}
});
});
});
I want use this code for list and filter my database but my database is realy huge like 9 or 10 gb. this code auto load all database to screen after filterin database . if ı use that my computer can error :D . ı want just load 10 item. how can ı do that ?
*
My Task is to get Nested DataTbless after making an ajax call.
I'm Getting the function working. Everytime I make a call it returns the data in main Datatable.
But, On Ajax call it gives me rowData is undefined error in Nested datatable.
Since I'm new at using Jquery I couldn't figure out the logical solution.
*
function ts_data(tabledata,tableChild,Expected_hrs,Hours_logged,Working_days,table_month){
$(document).ready(function() {
var table=$('#example').DataTable( {
"data": tabledata,
"retrieve": true,
"columns": [{
className: 'details-control',
orderable: false,
data: null,
defaultContent: ''
},
{ "data": "Fullname"},
{ "data": "Hours" },
{ "data": "Present_Hours_month"},
{ "data": "Working_Days" },
{ "data": "Month_Year"}],
"order": [[1, 'asc']]
} );
function format ( rowData ) {
console.log(rowData);
var file = jQuery.grep(tableChild, function(obj) {
return obj.Fullname === rowData.Fullname;});
var div = $('<table/>');
div.DataTable( {"paging": false,
"ordering": true,
"info": false,
"data": file,
"columns": [
{ "title": "Fullname", "data": "Fullname" },
{ "title": "Date","data": "Date" },
{ "title": "Day","data": "Day" },
{ "title": "Logged_Hours","data": "Logged_Hours" },
{ "title": "Present_Hours","data": "Present_Hours" }],
"order": [[1, 'asc']]})
return div;
}
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
});
};
function getMonth(){
$(document).ready(function() {
var month_yr = $('#recent').val();
$("#AjaxLoader").show();
$.getJSON('/attendance_log' + '/' + month_yr,
function(data) {
var tabledata = data.Main,
tableChild = data.Child,
Expected_hrs = data.Expected_hrs,
Hours_logged = data.Hours_logged,
Working_days = data.Working_days;
table_month = data.table_month;
console.log(tabledata);
/* Formatting function for row details - modify as you need */
document.getElementById("table_name").innerHTML = "Attendance log for " + table_month + " Month";
$("#AjaxLoader").hide();
ts_data(tabledata,tableChild,Expected_hrs,Hours_logged,Working_days,table_month);
});
})
}
var startDate = new Date();
$('.from').datepicker({
autoclose: true,
minViewMode: 1,
format: 'mm-yyyy'
}).on('changeDate', function(selected){
startDate = new Date(selected.date.valueOf());
startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
$('.to').datepicker('setStartDate', startDate);
});
window.onload = function(){
var today = new Date().toISOString().substr(0, 10);
var month_yr = today.substring(5, 7) +"-" + today.substring(0,4);
document.getElementById("recent").setAttribute("value", month_yr);
getMonth()
};
So I'm using jQuery child rows to display some data within a parent row. After displaying initially via Ajax, I do another ajax request and change data in the datatable. Now, if I try to expand it, it shows the rows. However, if I again try to change data in the datatable, it says d is not defined.
Here is my code when I initially load data in the datatable.
$.ajax({
url: "GetGridDetails?decodeID="+decoderFileSelected,
type: "GET",
dataType: 'json',
success: function (myData) {
if(myData != null){
console.log("my data is:"+myData);
var table = $('#dashNumTable').DataTable({
destroy: true,
data: myData ,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "S" },
{ "data": "W" },
{ "data": "SA" },
{ "data": "DDS" },
{ "data": "AAS" },
{ "data": "ABS" },
{ "data": "BIN" },
{ "data": "ET" }
],
"order": [[1, 'asc']]
});
// Add event listener for opening and closing details
$('#dashNumTable tbody').on('click', 'td.details-control', function () {
//alert("clicked plus!");
var tr = $(this).closest('tr');
var row = table.row(tr);
//var row = $('#dashNumTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
}//if code ends..
else{
alert("There are no base numbers for the selected decoder ring file...");
}
} //end of success function...
});
This generates table with a plus button to expand and minus button to contract.
Code to refresh and add new data when an ajax event is fired.
$(document).on("click", "#showHGAPartBtn", function(){
// clear the eixisting table contents
//alert("show button clicked!");
var decoderFileSelected = $("#decoderFile").val();
//$('#dashNumTable').empty();
// var clearTable = $('#dashNumTable').DataTable();
// clearTable.clear().draw();
//clearTable.rows().remove();
$('#dashNumTable').DataTable().ajax.reload();
//get the fresh data..
$.ajax({
url: "GetGridDetails?decodeID="+decoderFileSelected,
type: "GET",
dataType: 'json',
success: function (data) {
//if(myData != null){
//console.log("my data is:"+myData);
var table = $('#dashNumTable').DataTable({
// destroy: true,
cache: false,
processing: true,
data: data ,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "S" },
{ "data": "W" },
{ "data": "SA" },
{ "data": "DDS" },
{ "data": "AAS" },
{ "data": "ABS" },
{ "data": "BIN" },
{ "data": "ET" }
],
"order": [[1, 'asc']]
});
// Add event listener for opening and closing details
// $('#dashNumTable').on('click', 'tbody td.details-control', function () {
$('#dashNumTable').delegate('tbody td.details-control', 'click', function () {
//alert("clicked plus!");
var tr = $(this).closest('tr');
//table.ajax.reload();
var row = table.row(tr);
// alert("Row is :"+row);
//var row = $('#dashNumTable').DataTable().row(tr);
console.log(tr);
console.log(row);
console.log(row.child.isShown());
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
// }//if code ends..
// else{
// alert("There are no base numbers for the selected decoder ring file...");
//}
},
//end of success function...
error: function(response){
console.log(response);
}
});// end of AJAX call
Here is the format function, which returns error in second time.
function format (d) {
//alert(d.stringify);
//alert(JSON.stringify(d));
var rowSelectedBaseNumbers = d.HGA_BASE_NUMBERS;
// `d` is the original data object for the row
//alert(rowSelectedBaseNumbers);
var selectedBaseNumbersDropdown = $("#selBaseNumbers").val();
var initial = "<table cellpadding='0' cellspacing='0' class='innerDataTbl'><tr class='shown'> <th>Dash No.</th> <th>Heads</th>";
var finalReturn = "";
var endHeaders = "</tr>";
var middleContentHeaders = "";
//iterate over the base numbers now
for(var i=0;i< selectedBaseNumbersDropdown.length; i++){
middleContentHeaders += "<th>"+selectedBaseNumbersDropdown[i]+"</th>";
}
var beginTRCheckboxes = "<tr><td>"+d.DIGIT+0+","+d.DIGIT+1+"</td><td>Up,Dn</td>";
var endTRCheckboxes = "</tr>";
var endTable = "</table>";
//iterate over the total base numbers again to create respective checkboxes
var checkboxes = "";
for(var i=0;i< selectedBaseNumbersDropdown.length; i++){
//is the selected base number already selected?
if($.inArray(selectedBaseNumbersDropdown[i], rowSelectedBaseNumbers) == -1){
//not found
//display checkbox as it is
checkboxes += "<td><input type='checkbox'/></td>";
}
else{
//found
//mark checkbox already selected
checkboxes += "<td><input type='checkbox' checked='checked' disabled/></td>"
}
}
//generate final return now
finalReturn = initial+middleContentHeaders+endHeaders+beginTRCheckboxes+checkboxes+endTRCheckboxes+endTable;
return finalReturn;
}
The error returned is
typeerror - d is not defined
make a failSafe scenario in your format function for whenever no data is available, the code will not execute.
function format (d) {
if (d) { return null; }
...
}
Are you sure that the code
row.data()
actually returns a value? => Try to figure that out.
Also, what is d? Try to make your code as easy as possible to read. We developers are writers. Not for the computer, but for our colleagues who sometimes need to read our code to understand what we are trying to accomplish.
I have this DataTable defenition:
var availableFilesTable = $("#availableFiles").DataTable({
'processing': true,
'serverSide': true,
'ajax': '#Url.Action("GetAllBinariesExclude", "Program", new {programId = Model.Id})',
'columns': [
{
data: 'Id',
'checkboxes': {
'selectRow': true
}
},
{
'data': 'BinaryName'
},
{ 'data': 'Sha1Hash' }
],
'select': {
'style': 'multi'
},
'order': [[1, 'asc']]
});
I want to get all the selected rows and submit them to server, I have the following code for form submit event:
$('form').submit(function(event) {
event.preventDefault();
var form = this;
var existingFileIds = selectedFilesTable.column(0).checkboxes.selected();
var fileIndex = 0;
var newFiles = availableFilesTable.column(0).checkboxes.selected();
$.each(newFiles,
function(index, fileId) {
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'SelectedBinaryFilesIds[' + fileIndex + ']')
.val(fileId)
);
fileIndex++;
});
if ($(form).valid()) {
form.submit();
}
});
The problem is that when I put a debugger and inspect the content of newFiles it only contains the content of active page of DataTable, Any hint on what am I doing wrong? I want to get all the selected rows in all pages with server side rendering but with the following code I only get the selected rows in the active page.
any help is much appreciated.
When I click on the image in Reponsive mode, it will return the row data in console. But in normal view I get Undefined error.
var table = $('.dataTable').DataTable({
"responsive": true,
"columnDefs": [{
"targets": 4,
"data": null,
"render": function (data, type, full, meta) {
if (type === 'display') {
data = "<a href='#' width='30px' class='editMe' data='" + full[0] + "'><img src='/images/edit.png' width='30px' /></a>";
}
return data;
}
} ,
{
"targets": 0,
"visible": false,
"searchable": false
}]
});
$('.dataTable').on('click', '.editMe', function () {
console.log(table.row(this).data());
});
Use the code below instead:
$('.dataTable').on('click', '.editMe', function () {
var $row = $(this).closest('tr');
if($row.hasClass('child')){ $row = $row.prev(); }
console.log(table.row($row).data());
});
See this example for code and demonstration.