Finalizing editing in jqgrid - javascript

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

Related

Custom pasting into empty datatable

When I'm trying to paste into the empty area within the webix datatable, nothing happens and onPaste event doesn't occur.
Basically, I want to add a new item through onPaste even when existing data items aren't selected. But whether it's possible?
Something like the 'insert' operation in a list, but in my use-case the datatable can be empty after init (in the following sample I've added an item to make clipboard work). Here it is:
http://webix.com/snippet/9ae6635b
webix.ui({
id:'grid',
view:'datatable',
select:true,
clipboard:'custom',
editable:true,
columns:[
{ id:'id' },
{ id:'name', fillspace:true, editor:"text" },
{ id:'details' }
],
data: [
{ }
],
on:{
onPaste: function(text){
this.add({ id:webix.uid(), name:text })
}
}
});
Any suggestions are appreciated.
I found that 'clipbuffer' has focus only when datatable has the selection. Most probably it is required for data editing, detecting position or whatever. Anyway, the 'clipbuffer' can be focused manually:
var clipEvent = webix.event($$("grid").getNode(), "click", function(){
webix.clipbuffer.focus();
});
Sample: http://webix.com/snippet/aa441e70

Cannot retain checkbox value using jquery.cookie

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

JQGrid Add Double Submiting And Loosing Values

I have a sub grid that I'm adding values to. The problem is that it submits the first time fine. The second submit it goes through validation fine and then blanks out the checkbox values and submits them false. After submitting to the server it re-fires the validation and fails this time. It seems to be double bound but not sure how on this page.
Here is the subgrid editrow:
$("#" + subgridTbleId).jqGrid('editGridRow', "new",
{
addCaption: "Add Alert",
editCaption: "Edit Alert",
closeAfterAdd: true,
clearAfterAdd: true,
reloadAfterSubmit: true,
recreateForm:true,
viewPagerButtons: false,
width: 365,
beforeSubmit: function () {
if ($(arguments[1].selector + " .EditTable input:checked").length === 0) {
return [false, 'Must select an alert.']; //error
}
return [true, ''];
}
});
The form has a textbox and 6 checkbox.
I'm using jqGrid 4.6.0, and jquery 1.11.0
The problem was in the declaration of the subgrid. I was binding a click event on a button in the table header. I just needed to unbind the click event before rebinding it.

jEditable - How to bypass the submit in datepicker onselect event

I am using jeditable with datepicker and i wish to do some validation once user select a date before submit it to the database. I gone through the jeditable-datepicker.js and realized that the submission is triggered once onselect event happened. How can I include conditions in the event so invalid date wont be submitted to the database?
Here is my trial by using the onsubmit event:
$('.expirydatepicker').editable('#(Url.Action("Edit", "Stock"))',
{
type: 'datepicker',
indicator: 'saving...',
event: 'dblclick',
tooltip: 'Double click to edit...',
style: 'inherit',
width: ($('.datepicker').width() - 10) + "px",
onsubmit: function (settings, td) {
var tid = $(td).attr('id');
//alert(tid);
$.ajax({
async: false,
url: '/Stock/CompareDate',
type: 'GET',
data: { id: tid },
success: function (result) {
if (result < 0) {
alert("Expiry dare cannot be earlier than storage date");
return onSelect(false);
}
else {
return true;
}
}
});
}
});
the jEditable-datepicker function :
/* attach jquery.ui.datepicker to the input element */
plugin: function( settings, original ) {
var form = this,
input = form.find( "input" );
// Don't cancel inline editing onblur to allow clicking datepicker
settings.onblur = 'nothing';
datepicker = {
dateFormat: 'D, dd M yy',
onSelect: function() {
// clicking specific day in the calendar should
// submit the form and close the input field
form.submit();
},
I wish to know is there anyway I can either "stop" the onselect event if the input is invalid??
Hope can get some help here... thanks....
try something like this:
plugin : function(settings, original) {
..
$(this).find('input').datepicker().bind('click', function(e) {
//e.preventDefault() // also test this
return false;
})
Can you simply check whether the selected date is valid, and only submit and form if it is?
onSelect: function(dateText, inst) {
if (/* dateText is valid */) {
form.submit();
}
}
i get it done by not stopping the submission, but change the input value back to default value if validation failed. This is the only way I could get it done. Thanks!

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