jqGrid set dataURL Dynamically after Edit Form Loads - javascript

I am using jqGrid 4.15.6-pre - free jqGrid:
I have two dropdown list in my edit form.
Both are populated from server using the setColProp in the onSelectRRow function.
What I want to do reload the second dropdown list if the value in the first dropdown is changed.
I need to do this without having to close the edit form.

The example below uses the Guriddo jqGrid. You maybe can adapt it to the forked version - free-jqgrid.
$(document).ready(function () {
$("#jqGrid").jqGrid({
url: 'data.json',
editurl: 'clientArray',
datatype: "json",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 75,
key: true
},
{
label: 'Company Name',
name: 'CompanyName',
width: 140,
editable: true // must set editable to true if you want to make the field editable
},
{
label : 'Phone',
name: 'Phone',
width: 100,
editable: true
},
{
label: 'Postal Code',
name: 'PostalCode',
width: 80,
editable: true
},
{
name: 'Country',
width: 200,
editable: true,
edittype: "select",
editoptions: {
value: "USA:USA;UK:UK;Canada:Canada"
}
},
{
name: 'City',
width: 200,
editable: true,
edittype: "select",
editoptions: {
value: "Select a City"
}
}
],
loadonce: true,
viewrecorde: true,
width: 780,
height: 200,
rowNum: 10,
pager: "#jqGridPager"
});
$('#jqGrid').navGrid('#jqGridPager',
// the buttons to appear on the toolbar of the grid
{ edit: true, add: false, del: false, search: false, refresh: false, view: false, position: "left", cloneToTop: false },
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
recreateForm: true,
closeAfterEdit: true,
viewPagerButtons: false,
afterShowForm: populateCities,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
closeAfterAdd: true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
// This function gets called whenever an edit dialog is opened
function populateCities() {
// first of all update the city based on the country
updateCityCallBack($("#Country").val(), true);
// then hook the change event of the country dropdown so that it updates cities all the time
$("#Country").bind("change", function (e) {
updateCityCallBack($("#Country").val(), false);
});
}
function updateCityCallBack(country, setselected) {
var current = $("#jqGrid").jqGrid('getRowData',$("#jqGrid")[0].p.selrow).City;
$("#City")
.html("<option value=''>Loading cities...</option>")
.attr("disabled", "disabled");
$.ajax({
url: country+".html",
type: "GET",
success: function (citiesHtml) {
$("#City")
.removeAttr("disabled")
.html(citiesHtml);
if(setselected) {
$("#City").val( current );
}
}
});
}
});
Real-time example is here

Related

Empty Edit/Add windows on jQGrid for MVC

Although the jQGrid loads properly on the website, clicking the edit and add buttons brings up a window where I can't add the database information. It only shows the submit and cancel buttons on the bottom left.
I'm currently using this function for jQGrid:
$('#StudentGrid').jqGrid({
url: '#Url.Action("GetStudent", "Admin")',
editurl: '#Url.Action("GetStudent", "Admin")',
mtype: 'GET',
datatype: 'json',
iconSet: "fontAwesome",
caption: 'Database',
autoresizeOnLoad: true,
autoResizing: { compact: true },
prmNames: { page: "CurrentPage", rows: "PageSize" },
jsonReader: {
repeatitems: false,
id: "StudentId",
root: "rows",
page: "page",
total: "total",
records: "records"
},
hidegrid: false,
autowidth: true,
//width: 1250,
/*height: 800,*/
top:100,
gridView: true,
loadonce: true,
rowNum: 10,
scrollrows: true,
autoresizeOnLoad: true,
autoResizing: { compact: true },
viewrecords: true,
pager: '#pager',
pgbuttons: true,
colNames: ["StudentId", "Name", "Grade"],
colModel: [
{
name: 'studentId',
index: 'studentId',
editoptions: { readonly: 'readonly' },
width: 25,
hidden: false,
sortable: false
},
{
name: 'name',
index: 'name',
editoptions: { size: 25, maxlength: 20 },
hidden: false,
sortable: true,
width: 25,
align: "center"
},
{
name: 'grade',
index: 'grade',
hidden: false,
sortable: true,
width: 25,
align: "center"
}
],
postData: {
StudentId: $("studentId").val(),
Name: $("name").val(),
Grade: $("grade").val()
},
loadError: function (request, textStatus, errorThrown) {
handleError('An error occured trying to load the Database.', request, textStatus, errorThrown);
},
gridComplete: function () {
},
selectTimeout: 0, //for wait to prevent from onSelectRow event firing when actually it is a double click
onSelectRow: function (rowid, status, e) {
clearTimeout(this.selectTimeout);
this.selectTimeout = setTimeout(
function () {
if (status) {//select
;
}
else { //deselect
$('#StudentGrid').jqGrid("resetSelection");
}
},
250);
},
ondblClickRow: function (rowid, iRow, iCol, e) {
}
}).jqGrid('navGrid', '#pager', {
add: true,
del: true,
edit: true,
search: false,
refresh: false,
addfunc: function (id) {
updateRow("new");
},
editfunc: function (id) {
updateRow("edit");
},
delfunc: function (id) {
deleteRow(id);
}
}).jqGrid('gridResize', { minWidth: 1024, maxWidth: 2048, minHeight: 300, maxHeight: 450 });
Both the edit and add buttons use the following function:
//Add new record to grid or edit existing record.
function updateRow(id) {
var oper;
var rowData;
if (id == 'new') {
//add requested, set jqgrid value
oper = 'add';
}
else {
//edit requested, set jqgrid value
oper = 'edit';
//Get jqgrid row id
var rowId = $('#StudentGrid').getGridParam("selrow");
//Re-asign id to rowId
id = rowId
//Set row data
rowData = $('#StudentGrid').jqGrid('getRowData', rowId);
}
// Display the edit dialog below to the grid
var position = getDialogPosition();
$('#StudentGrid').editGridRow(id, {
top: position.top,
left: position.left,
width: 900,
height: 'auto',
mtype: 'POST',
modal: true,
autoresizeOnLoad: true,
autoResizing: { compact: true },
recreateForm: true,
closeAfterAdd: true,
closeAfterEdit: true,
reloadAfterSubmit: true,
ajaxOptions: { cache: false },
editData: {
StudentId: $("studentId").val(),
Name: $("name").val(),
Grade: $("grade").val()
},
onInitializeForm: function (form) {
$('input', form).keypress(
function (e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if (key == 13) {
e.preventDefault();
}
});
},
afterSubmit: function (response, postdata, formid) {
//if action canceled
var retObj = JSON.parse(response.responseText);
if (retObj && retObj.CancelAction > 0) {
alert(retObj.Message);
}
$("#StudentGrid").jqGrid("setGridParam", { datatype: "json" }).trigger("reloadGrid");
return [true, '', false]; // no error and no new rowid
},
afterComplete: function (response, postdata, formid) {
//Set fields to only readonly
$('#studentId').attr('readonly', 'readonly');
$("#StudentGrid").jqGrid("setGridParam", { datatype: "json" }).trigger("reloadGrid");
checkForError('An error occured trying to save Student record.', response, null, null, formid);
},
beforeShowForm: function (form) {
//Remove readonly - need to be editable when adding a new code value record to grid/db code values table
if (id == 'new') {
$('#studentId').removeAttr('readonly');
}
},
successfunc: function (data) {
return true;
},
beforeSubmit: function (postdata, formid) {
return [true];
}
});
}
The HTML for the table is:
<table style="width:90%;margin:5px;">
<tr style="vertical-align:top;">
<td>
<div style="margin-top:5px;"></div>
<div class="textborder">
<span>Student Database</span>
</div>
<table id="StudentId"></table>
<div id="pager"></div>
</td>
</tr>
</table>
This is my first time trying to use jQGrid, so are there any parts of the code I'm missing?
Not sure, but you should set your fields as editable. this is the property in colModel -> editable : true like this:
colModel: [
{
name: 'name',
index: 'name',
editable : true,
editoptions: { size: 25, maxlength: 20 },
hidden: false,
sortable: true,
width: 25,
align: "center"
},
....
Check the docs for editing

create button add delete edit jqgrid

I have created a jqgrid, and I was successful in creating add,delete,edit function by enabling these functions which belong to the jqgrid library. I want to create button add,delete,edit functions outside the table and here is my code:
<table id="list47"></table>
<div id="plist47"></div>
<script>
var mydata = JSON.parse('#DATA_QUERIED'),
editSettings = {
checkOnUpdate: true,
reloadAfterSubmit: false,
closeOnEscape: true,
savekey: [true, 13],
closeAfterEdit: true
},
addSettings = {
checkOnUpdate: true,
reloadAfterSubmit: false,
savekey: [true, 13],
closeOnEscape: true,
closeAfterAdd: true
},
delSettings = {
onclickSubmit: function () {
var $this = $(this), p = $this.jqGrid("getGridParam"), newPage = p.page;
if (p.lastpage > 1) {// on the multipage grid reload the grid
if (p.reccount === 1 && newPage === p.lastpage) {
// if after deliting there are no rows on the current page
// which is the last page of the grid
newPage--; // go to the previous page
}
// reload grid to make the row from the next page visable.
setTimeout(function () {
$this.trigger("reloadGrid", [{ page: newPage }]);
}, 50);
}
return true;
}
},
removeTheOptionAll = function (elem) {
// We use "value" in the searchoption property of some columns of the colModel.
// The option {"": "All"} neams "No filter" and should be displayed only
// in the searching toolbar and not in the searching dialog.
// So we use dataInit:removeTheOptionAll inside of searchoptions to remove
// the option {"": "All"} in case of the searching dialog
if (elem != null && typeof elem.id === "string" && elem.id.substr(0, 3) !== "gs_") {
// we are NOT in the searching bar
$(elem).find("option[value=\"\"]").remove(); // remove "All" option
}
};
$(document).ready(function () {
jQuery("#list47").jqGrid({
data: mydata,
datatype: "local",
autowidth: true,
height: 'auto',
rowNum: 15,
rowList: [5, 10, 20],
colNames: ['USER_ID', 'USER_NAME', 'LOGIN_NAME', 'PASSWORD', 'DESCRIPTION', 'GROUP_ID', 'EMAIL', 'ACTIVE', 'ORGANIZATION_ID'],
colModel: [
{ name: 'USER_ID', index: 'USER_ID', width: 100, },
{ name: 'USER_NAME', index: 'USER_NAME', width: 140,edittype: "textarea" },
{ name: 'LOGIN_NAME', index: 'LOGIN_NAME', width: 140,edittype: "textarea" },
{ name: 'PASSWORD', index: 'PASSWORD', width: 140,edittype: "textarea" },
{ name: 'DESCRIPTION', index: 'DESCRIPTION', width: 140,edittype: "textarea" },
{ name: 'GROUP_ID', index: 'GROUP_ID', width: 140,edittype: "textarea" },
{ name: 'EMAIL', index: 'EMAIL', width: 200,edittype: "textarea" },
{ name: 'ACTIVE', index: 'ACTIVE', width: 70, sorttype: "float",formatter: "number", editable: true },
{ name: 'ORGANIZATION_ID', index: 'RGANIZATION_IDz', width: 140, sorttype: "float",formatter: "number", editable: true }
],
cmTemplate: {editable: true, searchoptions: {clearSearch: false }},
pager: "#plist47",
viewrecords: true,
sortname: 'USER_ID',
gridview: true,
grouping: true,
rownumbers: true,
autoencode: true,
viewrecords: true,
ignoreCase: true,
caption: "Đây là ví dụ mẫu về Grid",
ondblClickRow: function (rowid) {
var $this = $(this), selRowId = $this.jqGrid("getGridParam", "selrow");
if (selRowId !== rowid) {
// prevent the row from be unselected on double-click
// the implementation is for "multiselect:false" which we use,
// but one can easy modify the code for "multiselect:true"
$this.jqGrid("setSelection", rowid);
}
$this.jqGrid("editGridRow", rowid, editSettings);
}
}).jqGrid("navGrid", "#plist47", {}, editSettings, addSettings, delSettings, {
multipleSearch: true,
overlay: false,
onClose: function () {
// if we close the search dialog during the datapicker are opened
// the datepicker will stay opened. To fix this we have to hide
// the div used by datepicker
$("div#ui-datepicker-div.ui-datepicker").hide();
}
}).jqGrid("filterToolbar", { defaultSearch: "cn" });
});
</script>
here is the picture of that code: picture 1
So I have add del edit at the bottom of the jqgrid, now I want to create a button outside jqgrid like:
picture 2
You can do this using the methods for insert, update delete. For update or delete you will need to get the selected id and call the method. By example the code for edit a row can look like this.
$("#button_edit").click( function() {
var selcted_row = $("#grid").jqGrid('getGridParam', 'selrow');
if(selected_row) {
$("#grid").jqGrid("editGridRow",selected_row, editSettings);
} else {
alert("please select row");
}
});
Do similar to delete and adding a row. Look at the documentation for the methods.

How to show(or not) a checkbox dynamically depending on another form value?

My objective is to create a checkbox on this form, but only show it depending on the value of a dropdown list.
{
//this is the drop down list value
key: false, label: 'T.Expediente', name: 'COD_DPTO_ORIGEN', editable: true,
edittype: 'select', /*editoptions: { value: $scope.settings.cbGridCodTipExpOp },*/ formatter: 'select', width: 5,
editrules: { required: false }, editoptions: { 'class': 'bg-required' },
},
{
//and this is the checkbox I had to create
key: false, label: 'Colaborativo', name: 'FLAG_COLABORATIVO', hidden: true, editable: true, edittype: 'checkbox',
formoptions: { label: '¿Colaborativo?' },
editrules: { edithidden: true },
editoptions: { value: "1:0", defaultValue: "0" },
},
The checkbox should only be shown when the value of the dropdown list is "13".
This form appears when the user decides to add a new register to a certain table.
Sorry I've changed some things because I can't show it, but they don't have anything to do with my question
showNavGrid: true, // Muestra o no Navgrid.
navTools: { add: true, edit: true, del: true, view: true, refresh: true, search: false },
prmAdd: {
closeOnEscape: true, closeAfterAdd: true, recreateForm: true,
id: 'ROWID',
url: AtUrlValue.XXXXXXXXX
editData: { __RequestVerificationToken: $rootScope.sAntiForToken },
beforeShowForm: function (form) {
$('#xxxxxx', form).show();
$('#xxxxxx', form).hide();
$('#xxxxxx', form).attr("disabled", false);
$('#tr_' + 'xxxx', form).hide();
//THIS is what i've tried
if ( $('#COD_DPTO_ORIGEN').val() == "13" ) {
$('#tr_FLAG_COLABORATIVO', form).show();
}
else {
$('#tr_FLAG_COLABORATIVO', form).hide();
}
},
It does work the way I did it but it only enters the if when the page loads, as it's on the event beforeShowForm. But I don't know how to make it dynamically, thanks!
you can listen to the change event in the list
$(document).on('change', '#tr_FLAG_COLABORATIVO', function(e){
//add your code
});

jqGrid with Related Tables in MySQL

Good morning,
I'm going back to php and javasvript after a long time, and I used jqGrid pluging to create the grids. What I used well, to edit high and modify without problem. I can find the problem when I want to use a table with related data.
The table is the fees of some affiliates, which are related to the affiliates themselves. To edit use the jqgrid form. I tried to put a select, so they choose the affiliate, but I do not load the data.
I have given it many laps and I do not know what could be happening to me. To say that I am a little rusty. Sorry if there are very fat failures.
I put my code.
Index.html:
<script type="text/javascript">
$(document).ready(function(){
jQuery("#tblCuotas").jqGrid({
url:'cargaCuotas.php',
editurl: "editCuotas.php",
datatype: 'json',
mtype: 'POST',
colModel:[
{
label: 'ID Cuota',
name: 'idCuota',
index:'idCuota',
width: 50,
key: true,
editable: true,
hidden: true
},
{
label: 'Num. Cuota',
name: 'NumD',
index:'NumD',
width: 50,
editable: true,
editoptions : { required: true, placeholder: "Número de Cuota requieredo"}
},
{
label: 'Num. Afiliado',
name: 'NumAfiliado',
index:'NumAfiliado',
width: 150,
editable: true,
edittype: 'select',
formatter:'select',
editoptions : { dataurl: 'afiliadosSelect.php' },
editrules : { required: true, placeholder: "Número de Cuota Afiliado"}
},
{
label: 'Nombre',
name: 'NOMBRE',
index:'NOMBRE',
width: 300,
editable: true
},
{
label: 'Cuota',
name: 'CUOTA',
index:'CUOTA',
width: 150,
editable: true,
editoptions : { required: true, placeholder: "Importe de la cuota requieredo"}
},
{
label: 'Mes',
name: 'MES',
index:'MES',
width: 120,
editable: true,
editoptions : { }
},
{
label: 'Año',
name: 'ANNO',
index:'ANNO',
width: 50,
editable: true,
editoptions : { }
},
{
label: 'Pago',
name: 'PAGO',
index:'PAGO',
width: 50,
editable: true,
edittype: 'select',
editoptions : { value: "Y:SI;N:NO" }
},
{
label: 'Forma Pago',
name: 'FormaPago',
index:'FormaPago',
width: 100,
editable: true,
editoptions : { }
}
],
loadonce: false,
width: window.innerWidth-20,
height: window.innerHeight-150,
pager: '#paginacion',
rowNum: 50,
rowList:[50,100,150],
sortname: 'NumD',
sortorder: 'asc',
viewrecords: true,
caption: 'CUOTAS'
});
jQuery("#tblCuotas").jqGrid('navGrid','#paginacion',
{edit:true,add:true,del:true},
// options for the Edit Dialog
{
html5Check : true,
editCaption: "The Edit Dialog",
recreateForm: true,
checkOnUpdate : true,
checkOnSubmit : true,
closeAfterEdit: true,
reloadAfterEdit:true,
reloadAfterSubmit:true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
},
buttons : [
{
side : "right",
text : "Afiliado",
position : "first",
click : function( form, params, event) {
alert("Custom action in search form");
}
}
]
},
// options for the Add Dialog
{
closeAfterAdd: true,
html5Check : true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
});
</script>
afiliadosSelect.php:
<?php
include "../class/tAfiliados.php";
echo '<script>alert("Custom action in search form");</script>';
$oAfiliado = new tAfiliados(1, 0, 1, 1);
$respuesta = $oAfiliado->selectAfiliados();
echo $respuesta;
?>
tAfiliados.php:
<?php
include 'tMySQL.php';
class tAfiliados
{
public function selectAfiliados()
{
$oMySQL = new tMySQL();
if ($oMySQL->bConnect)
{
$cSQL ="SELECT COUNT(*) AS cuantos FROM afiliados WHERE borrado=0";
$this->fila = $oMySQL->countQuery($cSQL);
$this->cuantos = $this->fila['cuantos'];
$query = "SELECT idAfiliado, NumAfiliado, NOMBRE FROM afiliados WHERE borrado=0 ORDER BY NOMBRE";
$result = $oMySQL->GetQuery($query);
$response ='<select>';
$i=0;
while( $i <= $this->cuantos ) {
$response .= '<option value="'.$result[$i]['NumAfiliado'].'">'.$result[$i]['NOMBRE'].'</option>';
$i++;
}
$response .= '</select>';
}
$oMySQL->Close();
return $response;
}
}
?>
Greetings and many thanks.
Please remove this line from your code:
echo '<script>alert("Custom action in search form");</script>';
This causes problem to load the data. The data should contain only html data and nothing more.
This echo causes the data to fail to load into the grid.
UPDATE:
Sorry, Just now I jhave look at your code. The JavaScript is case sensitive.
Please replace
editoptions : { dataurl: 'afiliadosSelect.php' },
With
editoptions : { dataUrl: 'afiliadosSelect.php' },
UPDATE2
I have prepared a demo with your settings and it works fine. Here is the link. Please check if your path to afiliadosSelect.php is correct in the related toy your file where the grid is. In this case you should get in console a error.

jqgrid cascading dropdown lists in pop up edit mode

I have two drop down lists, the first one gets populated from the database values and the second one(PriceCode) depends on what the user selects in the first one(CurrCd). My question is how do I populate that second list dynamically? I am trying to do it in dataEvents but have no way of referencing the second drop down list in edit mode. Is there a correct and logical way of doing so?
Here is my code so far:
grid.jqGrid({
datatype: 'local',
jsonReader: als.common.jqgrid.jsonReader('EntityCd'),
mtype: 'POST',
pager: '#billingPager',
loadonce: true,
colNames: ['Currency', 'Status', 'Bill Curr', 'Price Code'],
colModel: [
{
{ name: 'DefaultCurr', index: 'DefaultCurr', width: 20, sortable: false },
{ name: 'BillStatus', index: 'BillStatus', width: 13, sortable: false },
{
name: 'CurrCd', index: 'CurrCd', width: 20, sortable: false,
editable: true,
edittype: 'select', stype: 'select',
editoptions: {
dataUrl: als.common.getServerPath() + 'LegalEntitiesAjax/GetCurrencies',
dataEvents:[{
type:"change",
fn: function (e) {
//populate price code list here
//below does not work to populate PriceCode
$.ajax({
type: 'POST',
traditional: true,
contentType: 'application/json; charset=utf-8',
url: als.common.getServerPath() + 'LegalEntitiesAjax/GetPriceList',
data: JSON.stringify({ curcd: this.value }),
async: false,
success: function (data) {
for(i=0; i < data.length; i++) {
$('select#PriceCode').append('<option val=\"' + data[i].PriceCode + '">' + data[i].Description + '</option>');
}
},
error: function (val) { }
});
}
}],
buildSelect: function (data) {
var currSelector = $("<select id='selCurr' />");
$(currSelector).append($("<option/>").val('').text('---Select Currency---'));
var currs = JSON.parse(data);
$.each(currs, function () {
var text = this.CurName;
var value = this.CurCode;
$(currSelector).append($("<option />").val(value).text(text));
});
return currSelector;
}
}
},
{ name: 'PriceCode', index: 'PriceCode', width: 20, sortable: false, editable: true, edittype: 'select', stype: 'select'}
],
loadtext: 'Loading...',
caption: "Bill Entities",
scroll: true,
hidegrid: false,
height: 300,
width: 650,
rowNum: 1000,
altRows: true,
altclass: 'gridAltRowClass',
onSelectRow: webview.legalentities.billing.onBillingSelected,
loadComplete: function (data) {
if (data.length > 0)
{
}
var rowIds = $('#billingGrid').jqGrid('getDataIDs');
$("#billingGrid").jqGrid('setSelection', rowIds[0]);
},
rowNum: 1000
});
grid.jqGrid('navGrid', '#billingPager', {
add: ($("#dev").text() == "True" || $("#globalqc").text() == "True"),
edit: false,
del: false,
search: false,
refresh: false
},
{ // Edit Options
},
{ // Add Options
addCaption: 'Add New Billing Entity',
beforeInitData: function (formid) {
},
url: als.common.getServerPath() + 'LegalEntitiesAjax/AddBillingEntity/',
recreateForm: true,
closeAfterAdd: true,
reloadAfterSubmit: true
},
{ // Del Options
});
The old answer shows how one can implement the dependent selects. You use form editing. Thus the <select> element of PriceCode column of the form editing will have the id="PriceCode". You can use $("#PriceCode").html(/*new options*/); to change the options of <select> editing field of PriceCode column inside of change event handler of CurrCd column.

Categories