Cannot retain checkbox value using jquery.cookie - javascript

I use jQuery DataTable and there is a checkbox on the toolbar that is used for retrieving all records or not. As stateSave feature of DataTable does not work properly, I tried to use jquery.cookie in order to keep the checkbox value after reloading the DataTable (because the checkbox is redrawn dynamically on every reload) as shown below:
$(document).ready(function() {
$('#example').DataTable( {
//code omitted for brevity
"serverSide": true,
"ajaxSource": "/Student/GetStudents",
"fnServerData": function (sSource, aoData, fnCallback) {
/* Add some extra data to the sender */
aoData.push({ "name": "isAll", "value": $("#cbIsAll").is(":checked") });
$.getJSON(sSource, aoData, function (json) {
/* Do whatever additional processing you want on the callback, then tell DataTables */
fnCallback(json);
});
},
"fnDrawCallback": function() {
$("div.toolbar").html('<input type="checkbox" id="cbIsAll" name="demo" /> Get all records');
}
});
$(document).on('change', '#cbIsAll', function () {
var isClicked = $('#cbIsAll').is(':checked') ? true : false;
$.cookie('clicked', isClicked, { expires: 1 }); // expires in 1 day
table.ajax.reload();
$('#cbIsAll')[0].checked = ($.cookie('clicked') == "true") ? true : false;
});
});
After debugging the code I saw that although the $('#cbIsAll')[0].checked line is executed properly as true, the checkbox lost value later than this line. Could you please clarify me about where the mistake is? Or is there a better and smart way to keep the checkbox value?

There is no reason to use $.cookie in your case. In the checkbox change event, you can simply store the value of the checked state and use that to set the checked property of the new checkbox generated when you reload the table
var isChecked;
$(document).on('change', '#cbIsAll', function () {
// Store the current value
isChecked = $(this).is(':checked');
....
Then in the datatable's callback function, set the checked state of the checkbox
$('#cbIsAll').prop('checked', isChecked);

Related

how to enable and disable paging from jquery dataTables on button click

Following is the code found in data table website in order to remove the paging.
$(document).ready(function() {
$('#example').DataTable( {
"paging": false
} );
} );
My question is how to enable and disable paging on button click.
as when i call DataTable function second time to same table. It shows error that data table is already initiated and im calling it second time.
simply recreate the dataTable using destroy: true and paging:
I wanted to show only the first 10 rows of the table, but still be able to sort the whole table. But I also wanted the ability to click a link and show the whole table.
Here's what I did: (my table is "ka_ad")
First, turn on paging
table_ad = $('#ka_ad').DataTable({
paging: true,
});
Second (optional: I didn't want to display the datatable pagination links and element, so I hid them with css
#ka_ad_length{display: none;}
#ka_ad_paginate{display: none;}
Lastly, toggle the bPaginate setting (I have a button with an ID of "test"):
$('#test').click( function () {
//console.log(mytable.settings()[0]['oFeatures']['bPaginate'] );
if(table_ad.settings()[0]['oFeatures']['bPaginate'] == false)
{
table_ad.settings()[0]['oFeatures']['bPaginate'] = true;
$('#test').html('Show All Rows');
}
else
{
table_ad.settings()[0]['oFeatures']['bPaginate'] = false;
$('#test').html('Show Fewer Rows');
}
table_ad.draw();
});
Try like this.
var oTable;
$(document).ready(function() {
oTable = $('#example').DataTable( {
"paging": false
} );
$('.btn').click( function () {
oTable.paging= false;
oTable.fnDraw();
});
} );
try this:(but i don't guarantee, because, i haven't tested)
var oTable = $('#example').dataTable();
// get settings object after table is initialized
var oSettings = oTable.fnSettings();
oSettings.paging = false;
$(".button").click(function(){
oSettings.paging = !oSettings.paging;
});
https://www.datatables.net/forums/discussion/16373/enable-disable-features-after-initializing-the-table

How to dynamically enable/disable Responsive extension

I have a project where users need to be able to select whether or not the accompanying script activates Responsive extension of jQuery DataTables.
I want to add a dropdown menu in HTML that lets users choose whether option responsive is set to true or false in dataTable() initialization options.
I tried to add a separate function to select the value and used a global variable to get it to the dataTable() function but couldn't get that to work.
JavaScript:
$(document).ready(function(){
$("#example").dataTable({
"responsive": false,
"processing": false,
"serverSide": true,
"ajax": "scripts/university.php",
"columns": [
// ID
null, ........
*HTML**
<select id="selected2" onchange="myFunction()">
<option value="true">true</option>
<option value="false">false</option>
</select>
I tried adding a document.getElementById clause as the first line in the dataTable function but couldn't make it work.
What can I add to the existing function to make responsive option user selectable from the list on the HTML page?
SOLUTION
You need to destroy table to re-initialize it and enable/disable Responsive extension.
var dtOptions = {
responsive: true
};
var table = $('#example').DataTable(dtOptions);
$('#ctrl-select').on('change', function(){
dtOptions.responsive = ($(this).val() === "1") ? true : false;
$('#example').DataTable().destroy();
$('#example').removeClass('dtr-inline collapsed');
table = $('#example').DataTable(dtOptions);
});
NOTES
When the table is destroyed, Responsive extension leaves some classes (dtr-inline, collapsed), so I remove them manually before initializing the table again.
Also I suggest having all options in a separate object dtOptions to make re-initialization easier, that way you just need to toggle one option responsive.
DEMO
See this jsFiddle for code and demonstration.
Assuming that it is this DataTable plug-in then you can change the responsive setting in your myFunction. First,
var table = $('#example').DataTable(/* your current settings */);
then, in myFunction,
new $.fn.dataTable.Responsive( table, {
details: true
} );
Have you tried using an onChange event handler to get the value whenever there is a change in the dropdown selection? I would think using the onChange to toggle a variable value and assigning it to whichever dataTable key would work. Like so:
$(document).ready(function(){
var selected;
$('#selected2').onChange( function() {
selected = $(this).val();
}
$("#example").dataTable({
"responsive": false,
"processing": selected,
"serverSide": true,
"ajax": "scripts/university.php",
"columns": [
// ID
null, ........
JSFiddle
Well get rid of the obtrusive javascript or use it ( onchange="myFunction()")
$(document).ready(function(){
var selectedValue;
$('#selected2').change( function() {
selectedValue = $(this).val();
alert(selectedValue);
});
});

TypeError: oTable.fnReloadAjax is not a function - DataTables

i thought i will have no more problems with dataTables as its working now even the refresh.
Turns out some time it works in some places, but in some places it just give this stupid error.
TypeError: oTable.fnReloadAjax is not a function
Well i have a functon which adds new data in table, after success i want datatable to refresh.
it did work on other view but now As i have created this view, it is not working.
Im using Ignited Datatables.
i have a common.js file includes the datatables script. this script is working fine.
function commonDataTables(selector,url,aoColumns){
var responsiveHelper;
var breakpointDefinition = {
tablet: 1024,
phone : 480
};
oTable = selector.dataTable({
sPaginationType: 'bootstrap',
oLanguage : {
sLengthMenu: '_MENU_ records per page'
},
"autoWidth" : false,
"aoColumns":aoColumns,
"bServerSide":true,
"bProcessing":true,
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"sAjaxSource": url,
"iDisplayLength": 25,
"aLengthMenu": [[2, 25, 50, -1], [2, 25, 50, "All"]],
'fnServerData' : function(sSource, aoData, fnCallback){
$.ajax ({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
}); //end of ajax
},
'fnRowCallback': function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$(nRow).attr("data-id",aData[0]);
responsiveHelper.createExpandIcon(nRow);
return nRow;
},
fnPreDrawCallback: function () {
// Initialize the responsive datatables helper once.
if (!responsiveHelper) {
responsiveHelper = new ResponsiveDatatablesHelper(selector, breakpointDefinition);
}
},
fnDrawCallback : function (oSettings) {
// Respond to windows resize.
responsiveHelper.respond();
}
});
}
Then in my Codeigniter View file.
oTable = '';
//Data Tables Script Here.
var selector = $('#ManageTabs');
var url = "{{base_url()}}admin/configurations/listTabs_DT/";
var aoColumns = [
/* ID */ {
"bVisible": false,
"bSortable": false,
"bSearchable": false
},
/* Tab Name */ null,
/* Tab Order */ null,
/* Tab Desc */ null,
/* Actions */ null
];
commonDataTables(selector,url,aoColumns);
//End Of dataTables Script..
i am using oTable as global variable so defined the oTable outside the document.ready function
var oTable;
i know its a bad practice to use global variable but i wanted to find a work around to make the datatable refresh all the data.
Well this global variable Method did worked out for 1 view but in this next view i get the error which i told you already.
Here, below is the code of the button where in success it should have performed its duty but instead it gave error..
$('#createTabBtn').on('click', function(e){
//e.stopImmediatePropagation();
e.preventDefault();
var selector = $('#createTabModelForm');
HRS.formValidation(selector);
if(selector.valid()){
var formData = {
TabName : $("#cTabName").val(),
TabOrder : $("#cTabOrder").val(),
TabDesc : $("#cTabDesc").val()
};
$.ajax({
type:"post",
url:"{{base_url()}}admin/configurations/addNewTab/",
dataType:"json",
data: formData,
success: function(output){
if (output == true){
oTable.fnReloadAjax();
}
}
});
//Do Stuff After pressing the Create Button.
// Close the Modal
$('#addNewTabModal_ManageTabs').modal('hide');
// Reset All the TextBoxes and CheckBoxes
$("#createTabModelForm")[0].reset();
// Reset/Empty All the Select2 Dropdowns
//jQuery('.select2-offscreen').select2('val', '');
}
else{
//The Else Portion if you want Something else to Happen if not validated Form
}
});
Please can anyone know the best way to refresh the dataTables..
OMG, i forgot to add the fnReloadAjax.js file. i added that in first view but forgot to add in this view..
so anyone if face any problem like this, just see if the js file is attached.
being careless cost me my time but eventually problem solved.
But still there is a issue of Global Variable i mean i use global variable to refresh the grid.
if anyone has better option to use this fnreloadajax function. plz share.

Finalizing editing in jqgrid

I using jqgrid with great succes in the following way:
The data is loaded from the server as JSON
The user do inline editing
When a save-button is clicked all the data is serialized using:
var data = $("#mygrid").getRowData();
var datajson = JSON.stringify(data);
The problem with this aproach is that I will get the input elements in my json-data if the user has not pressed return or moved away from the edited cell. Is there any way to end edit mode i jqgrid?
You can use saveRow to save the data.
To use saveRow you have to know the row id of the current editable row. You can for example save the rowid of the current editing in a variable (before you call editRow) and use the value for calling of the saveRow method.
UPDATED: see the demo. First select some row, modify the values and then click on the "Save current editing row" button. You will see that the changes will be saves.
I have solved it by triggering "keydown" ENTER event on element:
editoptions: {
dataInit: function(elem) {
$(elem).datetimepicker({
dateFormat: "yy-mm-dd",
onClose: function(datetimeText, datepickerInstance) {
$(elem).trigger($.Event( "keydown", { keyCode: $.ui.keyCode.ENTER } ))
}
});
}
}
I use remote submit for each cell, and as I used "contenteditable" div for cell editor (for multiline text), i wanted to finish cell editing with ctrl-enter.
( Based on Oleg's answer and How to close cell-editor? and http://www.trirand.com/jqgridwiki/doku.php?id=wiki:cell_editing )
$(document).ready(function() {
var grid,currentCell;
$(".jqGrid_wrapper").on("keydown","div[contenteditable]",function (e) {
if (e.ctrlKey && e.keyCode == 13)
{
grid.jqGrid("saveCell",currentCell.iRow,currentCell.iCol);
return false;
}
return true;
});
grid=$("#table_list_2");
grid.jqGrid({
url: ...
cellEdit: true,
cellsubmit: 'remote',
cellurl: '..',
beforeEditCell: function(rowid, cellname, value, iRow, iCol) {
currentCell={
rowid:rowid, cellname:cellname, value:value, iRow:iRow, iCol:iCol
}
}
});
});

jqGrid with an editable checkbox column

When using jqGrid how do you force a cell to load in its editable view on page load as well as when it is clicked?
If you set up 'cell editing' like below, the check box only appears when you click on the cell.
{ name: 'MyCol', index: 'MyCol', editable:true, edittype:'checkbox', editoptions: { value:"True:False" },
cellEdit:true,
Also on clicking checkbox, is there a way of sending a AJAX post to server instantly rather than having to rely on the user pressing enter?
To allow the checkboxes to always be click-able, use the checkbox formatter's disabled property:
{ name: 'MyCol', index: 'MyCol',
editable:true, edittype:'checkbox', editoptions: { value:"True:False"},
formatter: "checkbox", formatoptions: {disabled : false} , ...
To answer your second question, you will have to setup an event handler for the checkboxes, such that when one is clicked a function is called to, for example, send an AJAX POST to the server. Here is some example code to get you started. You can add this to the loadComplete event:
// Assuming check box is your only input field:
jQuery(".jqgrow td input").each(function(){
jQuery(this).click(function(){
// POST your data here...
});
});
This is an old one but has a lot of view so I decided to add my solution here too.
I'm making use of the .delegate function of JQuery to create a late binding implementation that will free you from the obligation of using the loadComplete event.
Just add the following:
$(document).delegate('#myGrid .jqgrow td input', 'click', function () { alert('aaa'); });
This will late bind that handler to every checkbox that's on the grid rows.
You may have a problem here if you have more than one checkbox column.
I had the same problem and I suppose that I found a good solution to handle checkbox click immediately. The main idea is to trigger editCell method when user clicks on the non-editable checkbox. Here is the code:
jQuery(".jqgrow td").find("input:checkbox").live('click', function(){
var iRow = $("#grid").getInd($(this).parent('td').parent('tr').attr('id'));
var iCol = $(this).parent('td').parent('tr').find('td').index($(this).parent('td'));
//I use edit-cell class to differ editable and non-editable checkbox
if(!$(this).parent('td').hasClass('edit-cell')){
//remove "checked" from non-editable checkbox
$(this).attr('checked',!($(this).attr('checked')));
jQuery("#grid").editCell(iRow,iCol,true);
}
});
Except this, you should define events for your grid:
afterEditCell: function(rowid, cellname, value, iRow, iCol){
//I use cellname, but possibly you need to apply it for each checkbox
if(cellname == 'locked'){
//add "checked" to editable checkbox
$("#grid").find('tr:eq('+iRow+') td:eq('+iCol+') input:checkbox').attr('checked',!($("#regions").find('tr:eq('+iRow+') td:eq('+iCol+') input:checkbox').attr('checked')));
//trigger request
jQuery("#grid").saveCell(iRow,iCol);
}
},
afterSaveCell: function(rowid, cellname, value, iRow, iCol){
if(cellname == 'locked'){
$("#grid").find('tr:eq('+iRow+') td:eq('+iCol+')').removeClass('edit-cell');
}
},
Then your checkbox will send edit requests every time when user clicks on it.
I have one submit function that sends all grid rows to webserver.
I resolved this problem using this code:
var checkboxFix = [];
$("#jqTable td[aria-describedby='columnId'] input").each(function () {
checkboxFix.push($(this).attr('checked'));
});
Then I mixed with values got from the code below.
$("#jqTable").jqGrid('getGridParam', 'data');
I hope it helps someone.
I had shared a full code at the link below, you can take a look if you need it.
http://www.trirand.com/blog/?page_id=393/bugs/celledit-checkbox-needs-an-enter-pressed-for-saving-state/#p23968
Better solution:
<script type="text/javascript">
var boxUnformat = function ( cellvalue, options, cell ) { return '-1'; },
checkboxTemplate = {width:40, editable:true,
edittype: "checkbox", align: "center", unformat: boxUnformat,
formatter: "checkbox", editoptions: {"value": "Yes:No"},
formatoptions: { disabled: false }};
jQuery(document).ready(function($) {
$(document).on('change', 'input[type="checkbox"]', function(e){
var td = $(this).parent(), tr = $(td).parent(),
checked = $(this).attr('checked'),
ids = td.attr('aria-describedby').split('_'),
grid = $('#'+ids[0]),
iRow = grid.getInd(tr.attr('id'));
iCol = tr.find('td').index(td);
grid.editCell(iRow,iCol,true);
$('input[type="checkbox"]',td).attr('checked',!checked);
grid.saveCell(iRow,iCol);
});
});
</script>
In your colModel:
...
{name:'allowAccess', template: checkboxTemplate},
...

Categories