In JQGrid - How to set value in a field in edit dialog programmatically - jqgrid

I am using JQGrid with Spring + Hibernate in my web application. I have created a functionality wherein JQGrid opens an edit dialog for editing a selected row, wherein I have created a custom button. When a user clicks this custom button, a dialog box opens and user selects a row from this dialog. When user clicks 'Ok' control moves back to JQGrid Edit dialog.
I just want the selected value from the dialog for a field to be copied in the field in JQgrid edit dialog. I am able to get the value from the dialog in a global javascript variable, but not able to set it in the JQGrid edit dialog field. Please help me doing this.
Relevent code from my javascript file is pasted below:
function JQDialog(title, contentUrl, params) {
var dialog1 = $("#codesdlg").dialog(
{
autoOpen: false,
modal: true,
title: title,
zIndex: 1000,
close: function (e, ui) { dialog1.remove(); },
buttons: { "Ok": function ()
{
alert("Selected A/c Code: " + selAccode + ' - '+selAcDescr);
$('#TblGrid_list').$('#tr_acccode').val(selAccode);
dialog1.dialog("close"); }
}
});
dialog1.load(contentUrl, function () {
dialog1.dialog('open');
});
// dialog1.load(contentUrl).dialog('open');
};
$("#list").jqGrid('navGrid','#pager',{edit:true,add:true,del:true,search:true,refresh:false},
{
recreateForm: true, dataheight: 375, width: 400, height: 450, zIndex:75,
beforeShowForm: function(form) {$('#tr_ccode',form).hide();
$('Select<span class="ui-icon ui-icon-search"></span>')
.click(function(rowid, iRow, iCol, cellValue, e) {
JQDialog("Test Dialog","../acctmstmgmt/opendlg",rowid);
// var rowData = jQuery(this).getRowData(rowid);
// rowData.acccode = selAccode;
// $('#list').jqGrid('setRowData', rowid, rowData);
// $("#list").jqGrid("setCell", rowid, "acccode", selAccode);
// alert(selAccode);
// $('#trv_acccode').val(selAccode);
// window.open("../acctmstmgmt/opendlg", 'Dialog', 'width=700,height=300', top=500, left=500 );
}).addClass("fm-button ui-state-default ui-corner-all fm-button-icon-left")
.appendTo("#tr_acccode");
}
},
{
recreateForm: true, dataheight: 375, width: 400, height: 450, zIndex:75,
beforeShowForm: function(form) {$('#tr_ccode',form).show();
$('Select<span class="ui-icon ui-icon-search"></span>')
.click(function() {
alert('Clicked');
}).addClass("fm-button ui-state-default ui-corner-all fm-button-icon-left")
.appendTo("#tr_acccode");
}
},
{
},
{ // search
sopt:['cn', 'eq', 'ne', 'lt', 'gt', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
});
});
$.jgrid.edit = {
addCaption: "Add Codes Master",
editCaption: "Edit Codes Master",
bSubmit: "Submit",
bCancel: "Cancel",
bClose: "Close",
bYes : "Yes",
bNo : "No",
bExit : "Cancel",
closeAfterAdd:true,
closeAfterEdit:true,
reloadAfterSubmit:true,
modal:true,
msg: {
required: "is mandatory or required",
number: "is a number field. Enter a valid number",
minValue: "should not be less than ",
maxValue: "should not be more than "
},
errorTextFormat: function (response) {
if (response.status !== 200) {
return '<div style="overflow-y: scroll;">'+
"Error encountered while processing. Please check the accuracy of data entered.-" + response.status + " "+response.responseText
+ '</div>';
}
},

I have resolved the issue with following code
simply placed following code in the "Ok" button function
$('#acccode').val(selAccode);
here acccode is colModel field and selAcccode is global javascript variable from where value is placed in the edit form field.

Related

Jqgrid inline edit submits the html instead of typed text

Have the jqGrid as below, problem is that getting the input html on save, due to not focusing out of the jqgrid (may be).
$(mygridId).jqGrid({
url: url,
datatype: "json",
mtype: 'GET',
colNames: ['ID', 'Name', 'Description'],
colModel: [
{
name: 'Id',
index: 'Id',
hidden: true
},
{
name: 'Name',
index: 'Name',
width: 25,
editable: true
},
{
name: 'Description',
index: 'Description',
width: 25,
search: false,
editable: true
}
],
cellEdit: true,
rownumWidth: 40,
gridview: true,
sortname: "Id",
autoencode: false,
cellsubmit: 'clientArray',
onCellSelect: function (rowId, iCol) {
theRow = rowId;
theColumn = iCol;
},
afterEditCell: function (rowid, cellname, value, iRow, iCol) {
theColumn = iCol;
theRow = rowid;
},
beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
theColumn = iCol;
theRow = rowid;
},
jsonReader: {
repeatitems: false,
userdata: "rows",
page: "page",
total: "total",
records: "records"
}
});
$(mygridid).jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
When i add multiple rows, and click save button, focus won't be lost from the textbox, Hence, the saved value of the textbox will be
<input type="text" id="1_Description" name="Description" role="textbox" style="width: 98%;">
Any idea how to fix these?
Thanks in advace!
This is from same issue I answered elsewhere (see comments)...
This happens (sometimes) when inline (row or cell) editing is used in jqGrid. The implementation I used is https://github.com/free-jqgrid/jqGrid.
What happens is that the editor control is not cleared inside the "td" tag of the cell in the underlying "table" used by jqGrid. The cell will still show the entered/edited value once, but when the cell is entered again (clicked, tabbed, arrow keys, etc.), the text in the newly injected editor control will be the content (innerHTML?) of the "td" tag - which is the previous editor control HTML. This is what I see when this happens in both the grid and the HTML:
Note that this HTML is the TOP 2nd cell shown in the image, with the "ghost" editor in the cell.
<td role="gridcell" style="text-align: center; color: black; background-color: white;" aria-describedby="Grid_Col2" class="editable-cell" title="" tabindex="0">
<input type="text" autocomplete="off" maxlength="9" id="93_Col2" name="Col2" role="textbox" style="width: 100%; box-sizing: border-box;">
</td>
I cannot confirm "why", but I was able to resolve this by using setTimeout(). I know, I know... :-( It seems to have something to do with the "navigation" div element (header element) of the grid snapping focus back to it - I guess if the currently selected control doesn't have the "edited" CSS (and the header cannot be edited...), it won't/can't fully remove the input control?
The setTimeout() was put in the "afterEditCell" override (see code block below).
I also gained stability by having empty implementations of the most of the cell editing override functions:
afterEditCell: function (rowid, cellname, value, iRow, iCol) {
let rawInput = $("#" + this.id + " tbody>tr:eq(" + iRow + ")>td:eq(" + iCol + ") input, select, textarea");
rawInput.select();
rawInput.focus();
setTimeout(() => {
//TODO: I hate this, but not able to determine why focus goes back to the keyboard
// navigation DIV instead of the cell being edited. So, we have to force it. :(
// This may have something to do with the "trick" to process keydown on non-input
// elements: https://github.com/free-jqgrid/jqGrid/blob/master/js/grid.celledit.js line 530
rawInput.focus();
}, 100);
},
afterRestoreCell: function (rowid, value, iRow, iCol) {
console.log("afterRestoreCell: (" + iRow + ", " + iCol + ") " + value);
},
afterSaveCell: function (rowid, cellname, value, iRow, iCol) {
//console.log("afterSaveCell: (" + iRow + ", " + iCol + ") " + value);
},
beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
//console.log("beforeEditCell: (" + iRow + ", " + iCol + ") " + value);
},
beforeSaveCell: function (rowid, cellname, value, iRow, iCol) {
//console.log("beforeSaveCell: (" + iRow + ", " + iCol + ") " + value);
return value; // note that this is required here!
},
beforeSubmitCell: function (rowid, cellname, value, iRow, iCol) {
//console.log("saving cell with value:" + value);
}

free jqgrid 4.8 overlay issue when jqgrid inside modal dialog

I use free jqgrid 4.8.
I use the jqgrid inside a modal dialog.
When I try to use the delete button of the pager, all the dialogs are disabled.
http://jsfiddle.net/9ezy09ep
$(function ()
{
$("#Ecran").dialog(
{
dialogClass: 'Ecran',
autoOpen: false,
width: 500,
height:400,
modal: true,
open: function (event, ui) {
$("#jqGrid").jqGrid({
url: 'http://trirand.com/blog/phpjqgrid/examples/jsonp/getjsonp.php?callback=?&qwery=longorders',
mtype: "GET",
datatype: "jsonp",
colModel: [
{ label: 'OrderID', name: 'OrderID', key: true, width: 75 },
{ label: 'Customer ID', name: 'CustomerID', width: 150 },
{ label: 'Order Date', name: 'OrderDate', width: 150 },
{ label: 'Freight', name: 'Freight', width: 150 },
{ label:'Ship Name', name: 'ShipName', width: 150 }
],
viewrecords: true,
width: 480,
height: 250,
rowNum: 20,
pager: "#jqGridPager"
});
jQuery("#jqGrid").jqGrid('navGrid', '#jqGridPager', {
del: true, add: false, edit: false,
beforeRefresh: function () {},
afterRefresh: function () {}},
{}, // default settings for edit
{}, // default settings for add
{}, // delete
{}, // search options
{}
);
},
close:function () {}
});
});
Any ideas ? thanks
I think that the origin of the problem by using jqModal inside of jQuery UI dialog. jqGrid is jQuery plugin. So it don't use only CSS from jQuery UI. It don't use jQuery UI Dialogs.
I recommend you to include the line
$.fn.jqm = false;
to switch off jqModal module and to use jQuery UI functionality. See http://jsfiddle.net/9ezy09ep/7/. I will examine the problem more detailed later to improve the code of free jqGrid for the described test case.
UPDATED: I made some additional modifications in free jqGrid, which allows alternative solution. One can now use the code like
$.jgrid.jqModal = $.jgrid.jqModal || {};
$.extend(true, $.jgrid.jqModal, {toTop: true});
to change the behavior of jqModal module. The next demo shows the results http://jsfiddle.net/OlegKi/9ezy09ep/9/
jqGrid should utilize ui-dialog class when it creates modal dialog.
you will have to modify jquery.jqGrid.min.js file.
As per version 5.0.0 ,
Just add ui-dialog class to follwing line,
modal: { modal: "ui-widget ui-widget-content ui-corner-all ",
e.g.
modal: { modal: "ui-widget ui-widget-content ui-corner-all ui-dialog",
As per free jqGrid version,
Add ui-dialog class to following line,
dialog: {
...
window: "ui-widget ui-widget-content ui-corner-all ui-front",
...
e.g.
dialog: {
...
window: "ui-widget ui-widget-content ui-corner-all ui-front ui-dialog",
...

How do I configure a Kendo UI grid to use a DropDownList to edit a cell?

I'm having trouble configuring a `Kendo UI' grid to use a DropDownList as an editor. I have a JS Bin example to reproduce my behavior. The goal is to populate the BinNumber, PartNumber and StockNumber fields once a selection is made from the dropdown. Currently I can't even get the DropDown to bind to the recordset properly. If I make a selection and move to another field, I get [object Object] in the BinNumber field. If I go back in and make another selection, the BinNumber then sticks. I have read the documentation thoroughly but I am still thoroughly confused by it.
For the [object object] mess have a look at this post, there is an attribute introduced back in late 2013 dealing with this issue data-value-primitive="true". In the past I just used to re-map the selection back to ds manually, but the attribute does it all for you, I tested in you jsBin and works fine.
binDropdownEditor: function (container, options) {
$('<input data-text-field="BinNumber" data-value-field="BinNumber" data-value-primitive="true" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: viewModel.binDropDownDataSource
});
}
On change binding (please paste into your JSBin javascript tab):
var bins =["BinNumber:12121"];
var gridDS = new kendo.data.DataSource({
transport: {
read: function (e) {
e.success(bins);
}
},
schema: {
model: {
id:"Row",
fields: {
Row:{type:"string"},
BinNumber: {type:"string"},
PartNumber: {type:"string"},
StockNumber:{type:"string"}
}
}
},
pageSize: 50
});
var binDropDownDataSource = [
{ BinNumber: "12345",PartNumber:"P-2929",StockNumber:"S-06565" },
{ BinNumber: "23456",PartNumber:"P-2323",StockNumber:"S-956565" },
{ BinNumber: "34567",PartNumber:"P-4344",StockNumber:"S-67676" } ];
function appendEditor (container, options) {
$('<input data-text-field="BinNumber" data-value-primitive="true" data-value-field="BinNumber" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: binDropDownDataSource,
change:function(e){
var ddldataitem = this.dataItem();
var griditem = gridDS.at(0); // you might need to tweak this line
griditem.set("PartNumber",ddldataitem.PartNumber);
griditem.set("StockNumber",ddldataitem.StockNumber);
}
});
}
var grid= $("#bins").kendoGrid({
dataSource: gridDS,
scrollable: false,
autoBind:false,
batch:true,
editable : true,
navigatable: true,
toolbar: [ {name: 'custom-create', text: "Add New Line Item"}],
columns: [ {"field":"Row", title: "Row", width: "20px"},
{"field": "BinNumber","title":"Bin", editor: appendEditor},
{"field": "PartNumber", title: "Part ", width: "200px",editable: false },
{"field": "StockNumber", title: "Stock ", width: "200px",editable: false }
]
}).data("kendoGrid");
$(".k-grid-custom-create").on("click", function (e) {
gridDS.add({ Row:"1"});
});
The observable you had plugged in is not really necessary the underling data source is already observable, I have removed it. Please consider improving following line the index won't be always 0 var griditem = gridDS.at(0);
Here's how my DropDown is setup. This is a boolean field, so you will have to adjust it accordingly to your field
columns.Bound(m => m.IsInForecast).Title("Is Forecasted").ClientTemplate(
"# if (IsInForecast == true) { #" +
"<select id='#= OrderId #' onchange=save('#= OrderId #'); style='Width: 80px; color: 'navy' > " +
"<option id='yes' selected value='1'>Yes</option>" +
"<option id='no' value='0'>No</option>" +
"</select>" +
"# } else { #" +
"<select id='#= OrderId #' onchange=save('#= OrderId #'); style='Width: 80px; color: 'navy' > " +
"<option id='yes' value='1'>Yes</option>" +
"<option id='no' selected value='0'>No</option>" +
"# } #"
);

jquery ui dialog doesn't work with buttons

I'm trying to show a modal confirm dialog on delete link in a list action of a mvc 3 application.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#dialog-confirm").dialog({
autoOpen: false,
modal: true,
resizable: false,
height: 180
});
});
$(document).delegate(".deleteLink", "click", function (e) {
e.preventDefault();
alert('test');
var $link = $(this);
var $dialog = $('#dialog-confirm')
.dialog({
autoOpen: false,
modal: true,
resizable: false,
height: 180,
buttons: {
'button text': function () {
alert("button"); //this is the button, do something with it :)
}
}
});
$dialog.dialog('open');
});
<div id="dialog-confirm" title="Delete the item?" >
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This item will be deleted. Are you sure?</p>
and this is the link
#Html.ActionLink("حذف", "Delete", "Need", new { id = item.NeedID }, new { #class = "deleteLink", title = "حذف" })
when i remove the buttons option it works but when i add it , it doesn't show up anymore
where i'm doing wrong?
At a very quick glance - it would seem that buttons is an array. Try pasting in the sample from the documentation:
... {
autoOpen: false,
modal: true,
resizable: false,
height: 180,
buttons: [ { text: "Ok", click: function() { $( this ).dialog( "close" ); } } ]
}

jquery ui dialog in asp.net mvc3 doesn't open on second time

when i click the New Trade button in the form it opens jquery ui dialog. but, i have link button in the gridview when i click the link button it should open jquery ui dialog, it opens jquery ui dialog before clicking the new trade button. but, after clicking the new trade button, if i click link button in the gridview it invoke "ViewTradeDialog(id)" function, the dialog doesn't open, it shows error message "$vwdia.html(data).dialog is not a function". my code follows:
#using (Html.BeginForm("NewTrade", "Trade", FormMethod.Post, new { id = "searchForm" }))
{
<div id="searchbtn">
<input id="btn_newtrade" type="submit" value="New Trade" />
</div>
}
jquery code
<script type="text/javascript">
$(function () {
var $loading = $('<img src="../../loading.gif" alt="loading">');
var $dialog = $('<div></div>').append($loading);
$('#searchForm').submit(function (e) {
var url = this.action;
$.ajax({
autoOpen: false,
url: url,
success: function (data) {
$dialog.html(data).dialog({
zIndex:1,
width: 1400,
height: 600,
resizable: false,
title: 'New Trade Details',
modal: true,
buttons: {
"close": function () {
$dialog.dialog('close');
},
"Add Trade": function () {
$dialog.dialog('close');
$.ajax({
type: 'POST',
url: url
});
}
}
});
}
});
return false;
});
});
function ViewTradeDialog(id) {
alert(id);
var $vwdia = $('<div></div>');
var url = '/Trade/ViewTrades?tradeid=' + id;
$.ajax({
url: url,
success: function (data) {
$vwdia.html(data).dialog({
width: 600,
height: 600,
resizable: false,
title: 'View Trade Details',
modal: false,
buttons: {
"close": function () {
$vwdia.dialog('close');
}
}
});
}
});
return false;
}
You are probably overwriting the dialog plugin each time you click new trade, since it is applied to the same element:
$dialog.html(data).dialog(...
It is possible that by replacing the html of the dialog and reapplying the plugin that it is breaking. Are you seeing any other errors in the JS console?

Resources