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.
Related
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
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
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
});
I am using jqgrid. I want to allow people to use a checkbox in inline editing. There will not be any buttons like edit etc, As soon as he clicks the checkbox, it should be considered as committed on client side.
There is a checkbox which I want to always keep in edit mode. After user is done making changes, he will click on a submit button & full grid data will get posted to the server.
I expect that getGridParam method should give me the updated cell values. However it is not doing so.
I feel my problem is the onSelectRow method. somewhere I am missing the implementation to save the current row state. & hence in the getGridParam method. I am getting the original values.
Code :
var lastsel;
jQuery("#AcOpenDataGrid").jqGrid({
url: '/Admin/Role/GetMappedMenus',
viewrecords: true, sortname: 'Code', sortorder: "desc",
colNames: [
"Code",
"MenuName",
"Allow"
],
colModel: [
{ name: 'Code', width: 10, key: true, align: 'center', hidden: true },
{ name: 'MenuName', index: 'MenuName', width: 60, search: true, searchoptions: JQ_sopt_string, align: 'left' },
{ name: 'Allow', index: 'Allow', width: 30, editable: true,edittype:'checkbox',editoptions: { value:"True:False" },formatter:'checkbox', formatoptions: {disabled : false} ,search: true, searchoptions: JQ_sopt_string, align: 'center' },
],
height: '500',
autowidth: true,
rowList: JQ_Paging_Opt,
rowNum: JQ_RowNum_Opt,
pager: pager_selector,
datatype: 'json', mtype: 'GET',
cmTemplate: { title: false },
loadonce:true,
altRows: true,
jsonReader: { root: "rows", page: "page", total: "total", records: "records", repeatitems: false, userdata: "userdata", id: "Code" },
editurl: 'clientArray',
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery(grid_selector).jqGrid('restoreRow', lastsel);
//jQuery(grid_selector).jqGrid('saveRow', lastsel);
jQuery(grid_selector).jqGrid('editRow', id, true);
lastsel = id;
}
},
}).navGrid(pager_selector, { view: false, del: false, add: false, edit: false, search: false, refresh: true }
).jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: 'cn' });
});
$(".submit").click(function () {
var localGridData = $("#AcOpenDataGrid").jqGrid('getGridParam', 'data');
//To Do : Post Ajax here.
});
I found a solution here. Not exactly what I expected but it does serves my purpose.
Make a column be a checkbox
beforeSelectRow: function (rowid, e) {
var $self = $(this),
iCol = $.jgrid.getCellIndex($(e.target).closest("td")[0]),
cm = $self.jqGrid("getGridParam", "colModel"),
localData = $self.jqGrid("getLocalRow", rowid);
if (cm[iCol].name === "closed") {
localData.closed = $(e.target).is(":checked");
}
return true; // allow selection
},
I have bind the jqGrid from MVC controller , below is my jqgrid code . I want to export selected checkbox row data to csv , i have gone through all code's but every one providing sample local data, but i am binding from server to jqGrid,so when i select the checkbox rows in jqGrid and click on "Export " button the entire row should export to csv, can anybody have the solution ?
$('#jQGrid').jqGrid({
search: true,
multiboxonly: true,
colNames: ["PayloadCorrelationId", "Export", "Asset", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],
colModel: [
{ name: 'CorrelationId', jsonmap: 'CorrelationId', hidden: true, width: 2 },
{ name: "", editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "1:0" }, formatoptions: { disabled: false } },
{ name: 'Device', jsonmap: 'Device', width: 60 }, { name: 'DateReported', jsonmap: 'DateReported', width: 100 },
{ name: 'ErrorType', jsonmap: 'ErrorType', width: 85 },
{ name: 'Error', jsonmap: 'Error', width: 140 },
{ name: 'Latitude', jsonmap: 'Latitude', width: 80 }, { name: 'Longitude', jsonmap: 'Longitude', width: 80 },
{ name: 'Payloadurl', jsonmap: 'Payloadurl', width: 180, formatter: 'link' }],
cellEdit: true,
pager: jQuery('#divpager'),
rowList: [5, 20, 50, 100],
rowNum:5,
sortorder: "desc",
datatype: 'json',
width: 900,
height: 'auto',
viewrecords: true,
mtype: 'GET',
gridview: true,
loadonce: true,
url: '/DataIn/DataInSearchResult/',
emptyrecords: "No records to display",
onSelectRow: true,
onSelectRow: function (id, status) {
var rowData = jQuery(this).getRowData(id);
configid = rowData['CorrelationId'];
alert(configid);
// Add this
var ch = jQuery(this).find('#' + id + ' input[type=checkbox]').prop('checked');
if (ch) {
jQuery(this).find('#' + id + ' input[type=checkbox]').prop('checked', false);
} else {
jQuery(this).find('#' + id + ' input[type=checkbox]').prop('checked', true);
}
// end Add
rowChecked = 1;
currentrow = id;
},
loadComplete: function () {
var ts = this;
if (ts.p.reccount === 0) {
$(this).hide();
} else {
$(this).show();
$("#lblTotal").html($(this).getGridParam("records") + " Results");
}
}
});
Just to clarify, There must be any buttons on clicking which the csv will generate from the selected check box. If it is so then loop through the grid data to filter out checked rows. You can loop through the grid data easily on firing the button event. Based on the resultant data create the csv.