JQGrid: Dropdown, select the value, through addrow - javascript

In JQGrid I have used the dropdown column with the following code (in colModel):
{
name: 'CountryList', index: 'CountryList', width: 120, resizable: true,
sortable: false, editable: true, edittype: 'select', formatter: 'select',
formatoptions: {
disabled: false
},
editoptions: {
size : 1,
dataUrl : 'GetLists.ashx?Type=CountrLists&RegionID=2'),
dataEvents: [{
type: 'change',
fn: function (e) {
//$('input#Job_Number').val(this.value);
//alert(this.value);
}
}],
style: "width: 95%"
}
},
Problem:
When adding row (addrow), i want the added row to have the above mentioned dropdown column value selected, by passing a paramter (preferably value of select/option HTML control)
parameters =
{
rowID : undefined,
initdata: {
chkSave: "false", 'Label': 'test', people: 'Test person',
CountryList: '2', Notes: 'Test notes.'
},
position: "first",
useDefValues: true,
useFormatter: false,
addRowParams: { extraparam: {} }
};
$("#tbJQGrid").jqGrid('addRow', parameters);
Please provide some solution or alternatives.

To resolve this,used the "setColProp" property to modify the dataUrl:
$("#tbJQGrid").setColProp('CountryList', { editoptions: { dataUrl: 'GetLists.ashx?Type=CountrLists&RegionID=15' } });
Hope this helps.
Kindly add to the comments, in case better solution exist.

Related

how to use filterControl: 'select' with formatter

I am using bootstrap-table for working with data from my database.
I get my data in javascript and I wanted to filter by select and I have a formatter on each column
I tried some solutions but nothing worked.
exemple the filter of reglementation is empty
what do you think ?
My code
let defaultColumns = [{
field: 'id',
title: 'ID',
filterControl: "input",
visible: false
}, {
field: 'article',
title: 'Article N°',
filterType: 'input',
height: 1700,
filterControl: "input",
formatter: initialiseSelect,
}, {
field: 'reglementation',
title: 'RĂ©glementation',
searchable: 'true',
filterControl: 'select',
filterData: 'var:arrayReg',
formatter: initialiseSelectReglementation,
}, {
field: 'action',
title: 'Valider',
filterControl: "select",
filterData: 'var:arrayReg',
height: 700,
formatter: initialiseCheckbox,
}
];
to initialize the array
let options = {
url: ******,
method: 'GET',
locale: "fr-FR",
uniqueId: "id",
pagination: true,
showExport: true,
filterControl: true,
disableUnusedSelectOptions: true,
// showRefresh: true,
autoRefresh: true,
exportDataType: "all",
exportTypes: ['csv', 'excel'],
columns: defaultColumns,
};
//initialisation de table
initTable(options);

Kendo Grid Separate Popup Window Title & Buttons for Create & Edit

I want to change the title of the editable popup window based on whether it is being used to create or edit a grid item (I want the fields to be the same for both of them, though).
I have set the popup window's title in editable
editable: {
mode: "popup",
template: kendo.template($("#popupTemplate").html()),
window: {
title: "Add"
}
}
But I'm not sure how to differentiate between Edit and Add. The Edit button is in the columns:
command: [
{
name: "edit",
text: {
edit: "Edit",
update: "Save",
cancel: "Cancel"
}
}
]
and the Add button in the toolbar:
toolbar: [{name: 'create'}]
Notably, I've tried this to no avail:
toolbar: [
{
name: 'create',
click: function(){
alert("test");
}
},
]
I've also seen e.model.isNew() used under edit, but according to my compiler, this is not a function.
I've looked all over the internet and Telerik and found nothing. Am I missing something?
EDIT: Someone asked for the entirety of my grid code:
var grid = $('#grid').kendoGrid({
//dataSource: this.source,
dataSource: this.testData,
height: 550,
filterable: true,
sortable: true,
pageable: {
pageSize: 30,
buttonCount: 1
},
//toolbar: ["create", "destroy", "search"],
toolbar: [
{name: 'create'},
{name: 'destroy'},
{name: 'search'},
{template: "<input id='category' type='search' style='width: 250px; float: right;'/>"}
],
resizeable: true,
columns: [
{
field: 'Name',
title: 'Name',
filterable: true,
},
{
field: 'MCN',
title: 'P/N',
filterable: false,
},
{
field: 'ID',
title: 'ID',
filterable: true,
},
{
field: 'Type',
title: 'Type',
filterable: true,
},
{
field: 'Subtype',
title: 'Subtype',
filterable: true,
},
{
field: 'Value',
title: 'Value',
filterable: false,
},
{
field: 'Tolerance',
title: 'Tolerance',
filterable: true, //Number/letter combination causes problem?
},
{
command: [
{
name: "edit",
text: {
edit: "Edit",
update: "Save",
cancel: "Cancel"
}
},
{
name: "copy",
text: "Copy",
//click: function
}
],
title: " ", width: "250px"
},
],
editable: {
mode: "popup",
template: kendo.template($("#popupTemplate").html()),
// window: {
// title: "Add"
// }
},
selectable: "multiple, row", // Select multiples by drag or Shift-Click
edit: function(e){
var container = e.container;
var model = e.model;
//console.log(model.get("ID"));
// Changing the size of the container
$(e.container).parent().css({
//width: "1000px",
//height: "500px"
});
//May be able to simplify this with a for loop
// Changing Type input to a dropdown
var input = $('#dropType');
input.kendoDropDownList({
dataTextField: "Type",
dataValueField: "dropType",
dataSource: [{Type: 'One'}, {Type: 'Two'}, {Type: 'Three'}],
}).appendTo(container);
// Changing Subtype input into a dropdown
var input = $('#dropSubtype');
input.kendoDropDownList({
dataTextField: "Subtype",
dataValueField: "dropSubtype",
dataSource: [{Subtype: 'One'}, {Subtype: 'Two'}, {Subtype: 'Three'}],
}).appendTo(container);
}
});
To change the title you should use edit function of the grid like this:
$("#grid").kendoGrid({
dataSource: {...},
height: 550,
toolbar: ["create"],
columns: [
{
field: "",
title: '',
attributes: { style: "text-align:center;" },
headerAttributes: { style: "text-align: center;" }
},
{
command: [
{ name: "edit", text: 'Edit' },
],
title: 'tools',
width: "200px",
attributes: { style: "text-align:center;" },
headerAttributes: { style: "text-align: center;" }
}
],
editable: {
mode: "popup",
template: $("#template").html(),
},
edit: function(e) {
if (e.model.isNew()) {
e.container.kendoWindow("title", "Createee");
} else {
e.container.kendoWindow("title", "Updateee");
}
}
});
And for using the template, see this answer : Kendo UI Grid popup
Edit:
According to kendo : Kendo Forum , isNew
The isNew method returns true or false depending on the id value of that model.
If the id is still set to the default value then it will assume it is a New Model.
So I think your problem is because of your dataSource, and you should fill id before the fields property. like this :
dataSource: {
transport: {
read: {
url: ...
type: "POST", // The request type.
dataType: "json", // The data type of the returned result.
},
create: {...},
update: {...},
destroy: {...}
},
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false },
BankName: { type: "string", validation: { required: true } },
....
}
}
},
pageSize: 20
},
And here are two Samples: ( Sample 1 , Sample 2 )

Get Jqgrid Column checkbox cheked value using MVC

I have to implement one good looking Grid in MVC4+Razor. Till now I have done by using jqgrid. Since I am new to jQuery grid, can someone suggest how to get checked checkbox value in column of checkbox of some id? Can someone help me how I can get that checkbox checked values in jgrid? I am attaching my HTML and Javascript code. So please send me solution using sample code.
Javascript code:
(function ($) {
$('#JQGrid1').jqGrid({
url: '/ExamForm/GetSubjects/',
datatype: "json",
contentType: "application/json; charset-utf-8",
mtype: 'GET',
width: 950,
height: 150,
colNames:['SubjectID', 'SubjectName', 'GroupName', ' SubjectCode'],
colModel:[
{name: "SubjectID", width: 70, align: "center",
formatter: "checkbox", formatoptions: { disabled: false},
edittype: "checkbox", editoptions: {value: "Yes:No", defaultValue: "No"},
stype: "select", searchoptions: { sopt: ["eq", "ne"],
value: ":Any;true:Yes;false:No" },key:true },
{ name: 'SubjectName', index: 'SubjectName', width: 60 },
{
name: 'GroupName', index: 'GroupName', width: 60, editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true
},
{ name: 'SubjectUniversityCode', index: 'SubjectUniversityCode', width: 20 }
],
rowNum: 100,
//loadonce: true,
grouping: true,
groupingView: {
groupField: ['GroupName']
},
multiselect: true
});
})(jQuery);
Get Selected row i have use following function
function getSelectedRows() {
var grid = $("#JQGrid1");
var rowKey = grid.getGridParam("selrow");
if (!rowKey)
alert("No rows are selected");
else {
var selectedIDs = grid.getGridParam("selarrrow");
var result = "";
for (var i = 0; i < selectedIDs.length; i++) {
result += selectedIDs[i] + ",";
}
alert(result);
}
});

to add button which will redirect to View Page of current row in JQGrid

I am trying to add button instead of View column but i tried with formatter still button is not loading but records are coming for the rest of the columns.
Below is my code:
$(function () {
$("#grid").jqGrid({
url: "/Location/LocationsList1",
datatype: 'json',
mtype: 'Get',
colNames: ['Id', 'Country Name', 'State Name', 'City Name', 'Location Name','View'],
colModel: [
{ key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
{ key: false, name: 'CountryName', index: 'CountryName', editable: true },
{ key: false, name: 'StateName', index: 'StateName', editable: true },
{ key: false, name: 'CityName', index: 'CityName', editable: true },
{ key: false, name: 'Name', index: 'Name', editable: true },
{ key: false, name: 'View', index: 'View', editable: true,formatter:ViewButton }],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
viewrecords: true,
caption: 'Location',
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
});
});
function ViewButton(cellvalue, options, rowObject) {
var rowid= options.rowid;
var button = "<button class=\"viewLineItem\" id="+ rowid+">View Line Item</button>"
$('#' + rowid).die();
$('#' + rowid).live('click', function (rowId) {
alert("hi");
alert(rowId);
});
};
I am new to JqGrid and don't know how it works. Any guidance/Help will be appreciated.
The code has some problems
options has no rowid property, but it has rowId property. You should change options.rowid to options.rowId
The formatter will be called during building the HTML fragment of the grid body. No element of the grid exist at the moment on the page. Thus you can't use $('#' + rowid).live('click', ...); at the moment.
The formatter have to return the HTML fragment, which will be placed in the corresponding cell (inside of <td>). One misses return button; at the end of the formatter.
There are exist well-known name conversion in JavaScript. One should use functions, which starts with capital letter only if you define the constructor of the new class. You see that ViewButton will be displayed in the other color to distinguish classes from other function. You should rename ViewButton to viewButton to hold the standard name conversion of JavaScript.
It's better don't specify index property in colModel. In the same way one should not include the properties with the defaul value, like key: false. To specify common property for many columns you can use cmTemplate property.
One should reduce the number of global functions, because the functions will be considerd as the properties of window object.
instead of usage hidden column with name: 'Id' one can specify id: 'Id' property of jsonReader. You use repeatitems: false property, which means that every item of input data has properties CountryName, StateName and so on. The default name of the id property (the rowid - the id of <tr> elements) is id, but you use Id instead. The property id: "Id" informs jqGrid about it.
The modified code could be about the following
$(function () {
function viewButton(cellvalue, options, rowObject) {
return "<button class=\"viewLineItem\" id=\"" +
options.rowId + "\">View Line Item</button>";
}
$("#grid").jqGrid({
url: "/Location/LocationsList1",
datatype: 'json',
colNames: ['Id', 'Country Name', 'State Name', 'City Name', 'Location Name','View'],
colModel: [
{ name: 'Id', key: true, hidden: true },
{ name: 'CountryName' },
{ name: 'StateName' },
{ name: 'CityName' },
{ name: 'Name' },
{ name: 'View', editable: false, formatter: viewButton }
],
cmTemplate: { editable: true },
pager: '#pager',
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
viewrecords: true,
caption: 'Location',
emptyrecords: 'No records to display',
jsonReader: { repeatitems: false, id: "Id" }
});
$("#jqGridA").click(function (e) {
var $td = $(e.target).closest("tr.jqgrow>td"),
rowid = $td.parent().attr("id"),
p = $(this).jqGrid("getGridParam");
if ($td.length > 0 && p.colModel[$td[0].cellIndex].name === "View") {
alert(rowid);
}
});
});
The last part of the above code ($("#jqGridA").click(...);) register one click handler for the whole grid. If the user clicks on any cell then the event handler will be called because of event bubbling. The e.target gives as the DOM element, which was clicked (for example the <button>). By using closest we can go to the outer <td> element, which parent is the row (<tr>) of the grid. The .attr("id") of the row is the rowid. Such binding works more effectively as binding click handler to every button inside of the grid.
By the way jqGrid has already one click event handler. One can use beforeSelectRow callback, because it will be called inside of the click handler. One should only don't forget to return true from the beforeSelectRow callback to inform jqGrid that you allow to select the row. The callback beforeSelectRow has already rowid as the first parameter, which simplify our code a little. The final code will be
$(function () {
function viewButton(cellvalue, options, rowObject) {
return "<button class=\"viewLineItem\" id=\"" +
options.rowId + "\">View Line Item</button>";
}
$("#grid").jqGrid({
url: "/Location/LocationsList1",
datatype: 'json',
colNames: ['Id', 'Country Name', 'State Name', 'City Name', 'Location Name','View'],
colModel: [
{ name: 'CountryName' },
{ name: 'StateName' },
{ name: 'CityName' },
{ name: 'Name' },
{ name: 'View', editable: false, formatter: viewButton }
],
cmTemplate: { editable: true },
pager: '#pager',
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
viewrecords: true,
caption: 'Location',
emptyrecords: 'No records to display',
jsonReader: { repeatitems: false, id: "Id" },
beforeSelectRow: function (rowid, e) {
var $td = $(e.target).closest("tr.jqgrow>td"),
p = $(this).jqGrid("getGridParam");
if ($td.length > 0 && p.colModel[$td[0].cellIndex].name === "View") {
alert(rowid);
}
}
});
});

Capture change/click event of drop down in jqGrid

The click event on my drop down does not fire. I do not see an alert and when I add a breakpoint in Firebug, it does not reach the breakpoint. It does reach the click and double click events if I breakpoint those.
Specifically, when I:
Double click to edit a line
Pick the Customer Drop Down and pick something else
Move to another line
then the line
alert("I changed");
Does not run.
I wonder if it's because when I move to another line, the value gets reverted (even though I have commented out the restoreRow method)
Am I using the right event to capture when my drop down value changes (without having to change focus).
$(document).ready(
function () {
// This is executed as soon as the DOM is loaded and before the page contents are loaded
var lastsel;
// $ is short for JQuery which is in turn a super overloaded function that does lots of things.
// # means select an element by its ID name, i.e. below we have <table id="ts"
$("#ts").jqGrid({
//=============
// Grid Setup
url: 'Timesheet/GridData/',
datatype: 'json',
mtype: 'GET',
pager: $('#pager'),
rowNum: 30,
rowList: [10, 20, 30, 40, 80],
viewrecords: true,
imgpath: '/Content/themes/base/images',
caption: 'Timesheet',
height: 450,
// Column definition
colNames: ['hCustomer_ID', 'hProject_ID', 'hTask_ID', 'Date', 'Customer', 'Project', 'Task', 'Description', 'Hours', '$'],
colModel: [
{ name: 'hCustomer_ID', index: 'hCustomer_ID', editable: false, hidden: true },
{ name: 'hProject_ID', index: 'hProject_ID', editable: false, hidden: true },
{ name: 'hTask_ID', index: 'hTask_ID', editable: false, hidden: true },
{ name: 'tsdate', index: 'tsdate', width: 80, editable: true, datefmt: 'yyyy-mm-dd' },
{ name: 'Customer', index: 'Customer', width: 250, align: 'left', editable: true, edittype: "select",
editoptions: { dataUrl: 'Timesheet/CustomerList' },
dataEvents: [
{
type: 'click',
fn: function (e) {
alert("I changed");
}
}]
},
{ name: 'Project', index: 'Project', width: 250, align: 'left', editable: true, edittype: "select", editoptions: { dataUrl: 'Timesheet/ProjectList'} },
{ name: 'Task', index: 'Task', width: 250, align: 'left', editable: true, edittype: "select", editoptions: { dataUrl: 'Timesheet/TaskList'} },
{ name: 'Desc', index: 'Desc', width: 300, align: 'left', editable: true },
{ name: 'Hours', index: 'Hours', width: 50, align: 'left', editable: true },
{ name: 'Charge', index: 'Charge', edittype: 'checkbox', width: 18, align: 'center', editoptions: { value: "0:1" }, formatter: "checkbox", formatoptions: { disabled: false }, editable: true }
],
//=============
// Grid Events
// when selecting, undo anything else
onSelectRow: function (rowid, iRow, iCol, e) {
if (rowid && rowid !== lastsel) {
// $(this).jqGrid('restoreRow', lastsel);
lastsel = rowid;
}
},
// double click to edit
ondblClickRow: function (rowid, iRow, iCol, e) {
// browser independent stuff
if (!e) e = window.event;
var element = e.target || e.srcElement
// When editing, change the drop down datasources to filter on the current parent
$(this).jqGrid('setColProp', 'Project', { editoptions: { dataUrl: 'Timesheet/ProjectList?Customer_ID=' + $(this).jqGrid('getCell', rowid, 'hCustomer_ID')} });
$(this).jqGrid('setColProp', 'Task', { editoptions: { dataUrl: 'Timesheet/TaskList?CustomerProject_ID=' + $(this).jqGrid('getCell', rowid, 'hProject_ID')} });
// Go into edit mode (automatically moves focus to first field)
// Use setTimout to apply the focus and datepicker after the first field gets the focus
$(this).jqGrid(
'editRow',
rowid,
{
keys: true,
oneditfunc: function (rowId) {
setTimeout(function () {
$("input, select", element).focus();
$("#" + rowId + "_tsdate").datepicker({ dateFormat: 'yy-mm-dd' });
}, 50);
}
}
);
}, // end ondblClickRow event handler
postData:
{
startDate: function () { return $('#startDate').val(); }
}
}); // END jQuery("#ts").jqGrid
$("#ts").jqGrid('navGrid', '#pager', { view: false, edit: false, add: false, del: false, search: false });
$("#ts").jqGrid('inlineNav', "#pager");
}); // END jQuery(document).ready(function () {
REVISED WORKING CODE:
$(document).ready(
function () {
// This is executed as soon as the DOM is loaded and before the page contents are loaded
var lastsel;
// $ is short for JQuery which is in turn a super overloaded function that does lots of things.
// # means select an element by its ID name, i.e. below we have <table id="ts"
$("#ts").jqGrid({
//=============
// Grid Setup
url: 'Timesheet/GridData/',
datatype: 'json',
mtype: 'GET',
pager: $('#pager'),
rowNum: 30,
rowList: [10, 20, 30, 40, 80],
viewrecords: true,
caption: 'Timesheet',
height: 450,
// Column definition
colNames: ['hCustomer_ID', 'hProject_ID', 'hTask_ID', 'Date', 'Customer', 'Project', 'Task', 'Description', 'Hours', '$'],
colModel: [
{ name: 'hCustomer_ID', index: 'hCustomer_ID', editable: false, hidden: true },
{ name: 'hProject_ID', index: 'hProject_ID', editable: false, hidden: true },
{ name: 'hTask_ID', index: 'hTask_ID', editable: false, hidden: true },
{ name: 'tsdate', index: 'tsdate', width: 80, editable: true, datefmt: 'yyyy-mm-dd' },
{ name: 'Customer', index: 'Customer', width: 250, align: 'left', editable: true, edittype: "select",
editoptions: {
dataUrl: 'Timesheet/CustomerList',
dataEvents: [
{
type: 'change',
fn: function (e) {
alert("I changed");
}
}]
}
},
{ name: 'Project', index: 'Project', width: 250, align: 'left', editable: true, edittype: "select", editoptions: { dataUrl: 'Timesheet/ProjectList'} },
{ name: 'Task', index: 'Task', width: 250, align: 'left', editable: true, edittype: "select", editoptions: { dataUrl: 'Timesheet/TaskList'} },
{ name: 'Desc', index: 'Desc', width: 300, align: 'left', editable: true },
{ name: 'Hours', index: 'Hours', width: 50, align: 'left', editable: true },
{ name: 'Charge', index: 'Charge', edittype: 'checkbox', width: 18, align: 'center', editoptions: { value: "0:1" }, formatter: "checkbox", formatoptions: { disabled: false }, editable: true }
],
//=============
// Grid Events
// when selecting, undo anything else
onSelectRow: function (rowid, iRow, iCol, e) {
if (rowid && rowid !== lastsel) {
// $(this).jqGrid('restoreRow', lastsel);
lastsel = rowid;
}
},
// double click to edit
ondblClickRow: function (rowid, iRow, iCol, e) {
// browser independent stuff
if (!e) e = window.event;
var element = e.target || e.srcElement
// When editing, change the drop down datasources to filter on the current parent
$(this).jqGrid('setColProp', 'Project', { editoptions: { dataUrl: 'Timesheet/ProjectList?Customer_ID=' + $(this).jqGrid('getCell', rowid, 'hCustomer_ID')} });
$(this).jqGrid('setColProp', 'Task', { editoptions: { dataUrl: 'Timesheet/TaskList?CustomerProject_ID=' + $(this).jqGrid('getCell', rowid, 'hProject_ID')} });
// Go into edit mode (automatically moves focus to first field)
// Use setTimout to apply the focus and datepicker after the first field gets the focus
$(this).jqGrid(
'editRow',
rowid,
{
keys: true,
oneditfunc: function (rowId) {
setTimeout(function () {
$("input, select", element).focus();
$("#" + rowId + "_tsdate").datepicker({ dateFormat: 'yy-mm-dd' });
}, 50);
}
}
);
}, // end ondblClickRow event handler
postData:
{
startDate: function () { return $('#startDate').val(); }
}
}); // END jQuery("#ts").jqGrid
$("#ts").jqGrid('navGrid', '#pager', { view: false, edit: false, add: false, del: false, search: false });
$("#ts").jqGrid('inlineNav', "#pager");
}); // END jQuery(document).ready(function () {
Additionally it's unclear why you use both inlineNav and manual call of editRow inside of ondblClickRow? If you would select row and then click on the button from the navigator the dataUrl will not be adjusted.
The reason of the main problem which you describe is wrong usage of dataEvents. In the documentation of editoptions you will find the dataEvents is the property of editoptions like dataUrl for example. Currently you placed dataEvents on the wrong place in colModel.
I would recommend you additionally to read the answer which describe how you can use dataUrl which parameters depend on the current selected row. Additionally I would recommend you to verify that you set Cache-Control in the response of dataUrl (see the answer). Alternatively you can use anothe option described here.

Categories

Resources