I have a datatable populated with aaData. There is this last column which is action that again is populated with an array.
What i need to do is, by clicking an action link, I should pick up the column array value for that specific row where i clicked the action.
The action column is populated with below json format
[
{
"displayValue":"Browse",
"link":"svnpath/BacklogApp",
"displayIcon" : "browselogo"
},
{
"displayValue":"Source Code",
"link":"svnpath/BackLog/trunk/webapp-project/",
"displayIcon" : "svnlogo"
},
{
"displayValue":"Contributors: Vaibhav",
"link":"#contributors",
"displayIcon" : "people"
}
]
This is my action column which has three links - browse, source code and contributor. When i click the contributor icon, i should be able to get "Contributors: Vaibhav" this string.
Below is the JS code
$(document).on('click', '.contributor', function(e)
var aPos = tableAADataForContributors.fnGetPosition(this);
alert(aPos);
//if aPos returns an array in console, use first val at pos zero to get row data
var aData = tableAADataForContributors.fnGetData(aPos[0]);
alert(aData);
But on alert, my aPos is coming to be null whereas tableAADataForContributors is not null.
Also, this is how I am populating the datatable
$.ajax({
type: "GET",
url: url,
dataType: "json",
cache: false,
contentType: "application/json",
success: function(tablePropJSONData) {
var oTable = $('#genericTable').dataTable( {
"bProcessing": true,
"aaData": tableObj,
"sPaginationType" : "full_numbers",
"bJQueryUI" : true,
"bRetrieve" : true,
"bPaginate" : true,
"bSort" : true,
"aaSorting" : [[ 2, "desc" ]],
"iDisplayLength" : 50,
"bAutoWidth" : false,
"bStateSave" : false,
"aoColumns" : tablePropJSONData.aoColumns,
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
var lastColumnIndex = aData.length-1;
var actionColumnContent = renderActionColumn(aData[lastColumnIndex]);
$('td:eq('+lastColumnIndex+')', nRow).html(actionColumnContent);
}
});
tableAADataForContributors = oTable; // initializing for picking up contributors from datatable.
searchDataTable(oTable, searchTerm);
},
And likewise initializing a global variable tableAADataForContributors to be able to use it in onclick event later.
I am not able to do so. Please someone suggest a javascript code.
Thankfully, I was able to solve it myself. Just a little bit of here and there was needed.
Below code does the requirement
$(document).on('click', '.contributor', function(e){
var aPos = tableAADataForContributors.fnGetPosition( $(this).closest('tr')[0]);
//if aPos returns an array in console, use first val at pos zero to get row data
var aData = tableAADataForContributors.fnGetData(aPos);
var actionColumnData = aData[aData.length-1];
$.each(actionColumnData, function(i, value){
alert(value.displayValue)
});
Related
I'm using the Javascript Datatable with server side searching.
So:
var table = $('#myTable').DataTable({
responsive: true,
serverSide: true,
ajax: {
url: myUrl,
dataSrc: ''
},
fnServerData: function (sSource, aoData, fnCallback, oSettings)
{
oSettings.jqXHR = $.ajax({
url: myUrl,
success: function (json, status, xhr) {
//Do stuff
}
});
}
});
I build the url dynamically using options set on my form.
I would like a button on my form so I can manually trigger the fnServerData function. At the moment I have to type into the included search box.
e.g. <button ng-click="model.search()">Search</button>
Is this possible?
Thanks
Here is the code that I used for refresh the DataTable
var table = $("#gridId").dataTable();
//if you want to add extra parameters in the query
/*table.fnSettings().ajax.data = function (d) {
$.extend(d, jsonPostData);
};
*/
table.fnDraw(false);
I've found a solution:
var oTable = $('#myTable').dataTable();
oTable.fnFilter('');
With the latest DataTable, you need to use following in order to trigger server side call:
table.draw();
I was wandering if its possible to pass in a different parameter to a controller using Ajax.reload() in datatables.
thanks to another topic on stackoverflow, I was able to pass in parameter from my variable in to url.Action on creating the table new { cyfy = "_Switch" })".replace("_Switch",Switch)
Then on button click i change the state of the variable ( to 0 or 1 ) and call Ajax.reload() on my table.
The issues is that controller receives the same parameter value on each reload. It seems that this part is not run with the reload:
"ajax": {
"url": "#Url.Action("GetProjects", "mytool",new { cyfy = "_Switch" })".replace("_Switch",Switch),
"type": "get",
"datatype": "json"
},
I was wandering if there is a way to pass in different parameter value on datatables ajax.realod ?
Below bigger part of the code:
$("#toggle").change(function () {
if ($('#toggle').is(':checked') == true) {
Switch = 1
}
else {
Switch = 0
}
/////////////////
var oTable = $('#myDatatable').DataTable({
"bPaginate": false,
dom: 'Bifrtp',
"ajax": {
"url": "#Url.Action("GetProjects", "mytool",new { cyfy = "_Switch" })".replace("_Switch",Switch),
"type": "get",
"datatype": "json"
},
Solved.
The issue was that Ajax was adding timestamp to the request on the reload.
to solve this I have added cache : true, option while creating a table.
and then I am reloading the table using ajax.url
var testURL = CreateUrl("mytool/GetProjects?cyfy=") + Switch;
$('#myDatatable').DataTable().ajax.url(testURL).load();
please help me with this problem. I want to get the total amount of all pages from my datatable but it dont work at all.
The documentation say that,
api.column( 3 ).data(); // I can get all data like this
api.column( 3, {page: "current"} ).data(); // I can get just the current page
But I am putting in this way (api.column( 3 ).data()) and dont work to get all data from all pages, It is as I am putting api.column( 3, {page: "current"} ).data(); only;
Here the code:
$(document).ready(function() {
//datatables
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('Locacao/ajax_list')?>",
"type": "POST"
},
"pageLength": 10,
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Update footer
// Total over all pages
valor = api
.column( 3 ) //here should work but nothing
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Update footer
$( api.column( 3 ).footer() ).html(valor);
}
});
Thanks advance!!!
You're using server-side processing mode with "serverSide": true, where data is sent for current page only. That is why data for all pages is unavailable to jQuery DataTables, only the current page data.
You can change your server-side script to perform the calculations on the server side and send the required data as an additional data parameter which you can access later in a callback via ajax.json() API method.
I am struggling to figure out how to pass a <div id> to another javascript. For example, at the start of my page I have the following script which creates a div id tag that allows me to dynamically select and change content of the page.
$(document).ready(function() {
$("select").change(function() {
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#stats').attr('src', '/hardware/' + subFolder + '/stats/usage.txt');
$('#hostInfo').attr('src', '/hardware/' + subFolder + '/stats/host.txt');
$('#folderContent').show();
});
$.ajax({
url: 'getFolders.php',
type: 'GET',
dataType: 'json',
success: function(json) {
var $selectBox = $('#folderList');
$.each(json, function(i, value) {
$selectBox.append($('<option>').text(value).attr('value', value));
});
$selectBox.change();
}
});
});
This allows me to do the following - this creates a selector that a particular folder can be selected.
<div class="hidden-print">
<select id='folderList'></select>
</div>
When the folder list is selected above it allows me to change content like the items below:
like the above to another java script.
$(document).ready(function() {
$('#example3').DataTable( {
"processing": true,
"ajax": {
"url" : "../../reports/drives.txt",
"dataSrc" : ""
},
"columns": [
{ "data": "Hostname.Name" },
{ "data": "Name"}
]
} );
} );
When i select a folder above from the selector i would like the folder under the URL under the AJAX to be modified along with it to update it.
UPDATE
After looking at this a bit further I don't think my explanation fit very well.
$(document).ready(function() {
$("select").change(function() {
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#folderLogo').attr('src', '/server/' + subFolder + '/Logo/hardware.png');
$('#folderContent').show();
});
$.ajax({
url: 'getFolders.php',
type: 'GET',
dataType: 'json',
success: function(json) {
var $selectBox = $('#folderList');
$.each(json, function(i, value) {
$selectBox.append($('<option>').text(value).attr('value', value));
});
$selectBox.change();
}
});
});
var thisId = $('folderList').attr('id');
I want to take this variable which should be a single folder and use it on a script like the one below.
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#folderLogo').attr('src', '/server/' + subFolder + '/Logo/hardware.png');
I would like to take the "subfolder" and use it something like the following:
$(document).ready(function() {
$('#example3').DataTable( {
"processing": true,
"ajax": {
"url" : "/server/" + subfolder + "/Stats/Map.txt",
"dataSrc" : ""
},
"columns": [
{ "data": "Hostname.Name" },
{ "data": "Name"}
]
} );
} );
I tried to get the method below to get a div id conversion and it doesn't have any data when i try it that way. I should have stated i want to use the variable in the sub folder in the script above... I tried a window.variable name i have tried the global variable and still nothing seems to be working correctly. My guess is that the way the variable is being processed is not carrying over.
You can access the id using $('#folderList').attr('id').
Assign that to a variable and pass it into your function. If you are loading a separate script using $(document).ready(), it may not be available unless it's a global variable.
Something like this might do the trick for you.
var thisId = $('#folderList').attr('id');
$(document).ready(function() {
$('#'+thisId).append('whatever');
} );
You can also pass it inside jQuery function using window.variable = value that will be considered as a global variable for that window object.
With your help i was able to diagnose and find the issue. When the variable is outside of the function it doesn't run. By adding it into the document.ready function it will keep the variable through changes of the dropdown. Then finding that because there are multiple initializations of the data-tables structure - i have to add the "destroy" flag = true. This destroys the old datatables and allows a new one to be created after you change the folder.
$(document).ready(function() {
$("select").change(function() {
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#folderLogo').attr('src', '/hardware/' + subFolder + '/Logo/hardware.png');
$('#hdstats').attr('src', '/hardware/' + subFolder + '/hdstats/hdstats.csv');
$('#folderContent').show();
$('#example3').DataTable( {
"destroy": true,
"processing": true,
"ajax": {
"url" : "/hardware/" + subFolder + "/hdstats/stats.txt",
"dataSrc" : ""
},
"columns": [
{ "data": "Hostname.Name" },
{ "data": "Name"}
]
} );
});
$.ajax({
url: 'getFolders.php',
type: 'GET',
dataType: 'json',
success: function(json) {
var $selectBox = $('#folderList');
$.each(json, function(i, value) {
$selectBox.append($('<option>').text(value).attr('value', value));
});
$selectBox.change();
}
});
});
Here is what i am trying http://jsfiddle.net/wQysh/347/
JS :
$.fn.editable.defaults.mode = 'inline';
var count = 4, sources = [];
for(var i = 1; i <= count; i++){
sources.push({ id : i, text : 's-'+String(i) })
}
var getSource = function() {
//i want this function must be called whenever available options is rendred. to ensure NO references issues, i used JSON.parse
return JSON.parse(JSON.stringify(sources));
};
var getQuery = function(options){
options.callback({ results : getSource() });
};
var getInitSel = function(multiple) {
return function(el, cb){
var t, toSet = [], sc = getSource();
el[0].value.split(',').forEach(function(a){
t = _.findWhere(sc, { id : Number(a.trim()) });
if(t) toSet.push(t);
});
cb(multiple ? toSet : (toSet.length ? toSet[0] : null));
};
};
$('#controller').click(function(e){
count++;
sources.push( {id : count, text : 's-'+String(count) });
$('#username').editable('option', 'source', getSource()); // <---------------- THIS LINE HAS NO EFFECT SO PRODUCING UNDESIRED RESULT
//with above line, the source option should get updated and should be handing the new records to render. but nothing happens such.
$('#username').editable('setValue', [1, count]);
});
$('#username').editable({ //to keep track of selected values in multi select
type: 'select2',
url: '/post',
autotext : 'always',
source : getSource(),
value : [1,2],
emptytext: 'None',
select2: {
multiple : true,
initSelection : getInitSel(true),
query :getQuery
}
});
//ajax emulation. Type "err" to see error message
$.mockjax({
url: '/post',
responseTime: 400,
response: function(settings) {
if(settings.data.value == 'err') {
this.status = 500;
this.responseText = 'Validation error!';
} else {
this.responseText = '';
}
}
});
I am just trying to update the source option of editable element via a controller. But the view doesn't reflect the same.
Any solution??
just added display function with iDkey as 'id'
$('#username').editable({ //to keep track of selected values in multi select
type: 'select2',
url: '/post',
autotext : 'always',
source : getSource(),
value : [1,2],
emptytext: 'None',
display: function(value, sourceData) {
//display checklist as comma-separated values
var html = [],
checked = $.fn.editableutils.itemsByValue(value, getSource(), 'id'); // it was needed to send 'id' as idKey otherwise it was fetching with value
if(checked.length) {
$.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); });
$(this).html(html.join(', '));
} else {
$(this).empty();
}
},
select2: {
multiple : true,
initSelection : getInitSel(true),
query :getQuery
}
});
here is working code http://jsfiddle.net/wQysh/351/
Every time we 'setValue' to editable or on close event editable's 'display' function is called.
in display function existing values is checked by this function
$.fn.editableutils.itemsByValue
where the third parameter accepts the idKey. If we do not provide third parameter while calling this function, it by default takes 'value' as idKey. and 'value' as idKey should not be used when we are using to load array data. ref : http://ivaynberg.github.io/select2/#data_array.