Showing serial number in jqgrid - javascript

I want to show serial number as first column in jqgrid.since, database records doesn't has contigous 'ids', I can't use it.
Is there any simple way to accomplish this?
Update:
sample code:
$(document).ready(function()
{
$("#list").jqGrid(
{
url:'<%=Url.class_variable_get(:##baseurl) %>/address_books/show.json',
datatype:'json',
mtype:'get',
colNames:['Id','Name','Email Id','Number'],
colModel:[
{name:'address_book_id',index:'address_book_id',sorttype:'int',sortable:true,width:100},
{name:'name',index:'name',sortable:true,width:300},
{name:'email',index:'email',sortable:true,width:265},
{name:'number',index:'number',sorttype:'int',sortable:true,width:300},
],
pager:$('#pager'),
emptyrecords: "No Records to display",
pginput:true,
pgbuttons:true,
rowNum:10,
rowList:[5,10,20,30],
viewrecords:true,
sortorder: "desc",
//multiselect:true,
loadonce:true,
gridview:false,
sortname:'name',
caption: " Contacts List",
jsonReader: {
repeatitems : false,
cell:"",
id: "0"
},
height: 80
});
$("#list").jqGrid('navGrid','#pager',{edit:false,add:false,del:false,search:true},{multipleSearch:true});
});

This question/answer should contain information on how to redraw the jqgrid based on redefined table data: jqGrid add new column
Regarding the addition of a you might add a time stamp to each of the records, or even the value of a counter; something like:
var recordsSet = [];
$.each(databaseRecords, function(i, record) {
record.idx = Date.now();
record._id = i;
recordSet.push(record);
});
/* code to populate or redraw using update recordSet array jqgrid here */
You shoud then be able to assign either the _id field or the idx field (sample property names only) to the index property of your column models in the call to jqgrid.

Related

Setting id attribute to datatables 1.10.11 <tr>

I am using datatables 1.10.11.
As per the documentation, i can set the rowId using following syntax:
$('#myTable').DataTable( {
rowId: 'staffId'
} );
I am not creating datatable using Ajax.
I have two text boxes and "Add" button on left hand side and one datatable on right hand side. When i click on "Add", a new row is added to datatable. I hope that makes sense.
I need unique id attribute for each row for my use. I have tried doing so but no success at all.
According to documentation, this feature is available since DataTables 1.10.8
Did anyone solved this problem? Any help will be appreciated.
Thanks.
For add ID to tr element you con use rowId and especify the column that contain your id.
$('#myTable').DataTable(
{
columns: [
{data:"staffId"},//Remember specified the column
{data:"position"},
{data:"office"},
{data:"age"},
{data:"date"},
{data:"salary"}
],
rowId: 'staffId' //Reference to column data
});
For your button add, you should create the object and add to Table using row.add and draw for show in your table, for example:
$("#btnAdd").on("click",function(){
var rowID = $("#rowId").val();//Get value of TextBox
var new_object = {
staffId: rowID, //New rowId
position: 'Developer',
office: "Peru",
age: 25,
date: "2016/03/25",
salary: "$ 58.200"
};
myTable.row.add(
new_object
).draw();
});
Result: https://jsfiddle.net/cmedina/7kfmyw6x/65/

In JQGrid, How can I dynamically get the column header label when validating a filtertoolbar field?

I have a jqGrid with the filtertoolbar option enabled. For a column or columns in the grid, I want to validate the column in some fashion, e.g., if an input field exceeds a certain length, display an alert.
When I display an alert, I want to display the column header label in colNames to a user, not the colmodel name for that input field, as that will be clearer to the user. I have a jsfiddle example with a simple example for the "Client Name" field. "Client Name" is hard-coded in the alert message. Ideally, I don't want to hard-code the label as it could change, e.g., "Client Name" could be changed to "Customer Name". I don't want to go back into the function to change it each time. Changing it in one place is trivial, but I may have a grid with several columns and associated functions involving the filter toolbar fields, and changing the labels across everywhere is inefficient.
I have searched the jqGrid documentation but have not found a function to do this. I know that the column labels are enclosed in divs named as jqgh_{grid name}_{column name}, e.g., jqgh_test1_name in the jsfiddle, and I can get the div contents, but I would have to parse out the label from the rest of the content, which seems like more work than is needed. Is there a built-in capability in jqGrid to do this, or will I have to parse the label from the div, or is there another approach that I can take?
Thanks in advance...
<table id="test1"></table>
.ui-widget { font-size: 0.8em }
$("#test1").jqGrid({
datatype: "local",
height: 250,
colNames:['Inv No','Date', 'Client Name', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:60, sorttype:"int"},
{name:'invdate',index:'invdate', width:90, sorttype:"date", formatter: 'date', formatoptions: {newformat: 'm/d/Y', srcformat: 'Y-m-d'}},
{name:'name',index:'name', width:100},
{name:'amount',index:'amount', width:80, align:"right",sorttype:"float"},
{name:'tax',index:'tax', width:80, align:"right",sorttype:"float"},
{name:'total',index:'total', width:80,align:"right",sorttype:"float"},
{name:'note',index:'note', width:150, sortable:false}
],
multiselect: true,
caption: "Manipulating Array Data"
});
$("#test1").jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: true,
defaultSearch: "cn",
});
var maxNameLength = 10;
$("input[id=gs_name]").blur(function () {
if (this.value.length > maxNameLength) {
alert('Client Name is longer than ' + maxNameLength + ' characters.');
}
});
$('#gs_invdate').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true
});
var mydata = [
{id:"1",invdate:"2007-10-01",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"},
{id:"2",invdate:"2007-10-02",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"},
{id:"3",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"},
{id:"4",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"},
{id:"5",invdate:"2007-10-05",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"},
{id:"6",invdate:"2007-09-06",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"},
{id:"7",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"},
{id:"8",invdate:"2007-10-03",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"},
{id:"9",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"}
];
for(var i=0;i<=mydata.length;i++)
$("#test1").jqGrid('addRowData',i+1,mydata[i]);
There are many ways to implement your requirement the modified demo http://jsfiddle.net/OlegKi/ejnrtocw/20/ for example use the following code for example
$("input[id=gs_name]").blur(function () {
var $th = $(this).closest(".ui-search-toolbar>th"),
colIndex = $th[0].cellIndex,
$colHeader = $th.parent().siblings(".ui-jqgrid-labels").children("th").eq(colIndex),
colHeaderText = $colHeader.children("div").text();
if (this.value.length > maxNameLength) {
alert(colHeaderText + ' is longer than ' + maxNameLength + ' characters.');
}
});
where the first two lines are the mostly important. colIndex exists in every <td> and <th> element and gives us the position (0-based) in the patent. So colIndex is the column index So one can use it as the index of colNames parameter to access the column text:
$("input[id=gs_name]").blur(function () {
var $th = $(this).closest(".ui-search-toolbar>th"),
colIndex = $th[0].cellIndex,
p = $("#test1").jqGrid("getGridParam"),
colHeaderText = p.colNames[colIndex];
if (this.value.length > maxNameLength) {
alert(colHeaderText + ' is longer than ' + maxNameLength + ' characters.');
}
});
See the next demo http://jsfiddle.net/OlegKi/ejnrtocw/21/

updated value in grid is not shown at java spring controller

I have a enhanced grid, i want to edit the grid contents and once clicked on Update link, i have to pass newly typed values to the java spring controller where i have logic to save updated values in database. But issue is after i type the value in enhanced grid i need to click somewhere in the grid or make focus on other field so that newly typed value is passed to the spring controller. If i type the new value and the cell is in edit mode and directly click on UPDATE link present in column4 of grid, the old value is passed to the spring controller. Please suggest what changes to be made so that once the mouse is out of the focus of the cell, the newly typed value should save in store and that value should be sent to spring controller when UPDATE link is clicked on column4 of grid.
Please find the fiddle : http://jsfiddle.net/740L0y43/7/
enhanced grid code:
require(['dojo/_base/lang', 'dojox/grid/EnhancedGrid', 'dojo/data/ItemFileWriteStore', 'dijit/form/Button', 'dojo/dom', 'dojo/aspect', 'dojo/domReady!'],
function (lang, EnhancedGrid, ItemFileWriteStore, Button, dom, aspect) {
/*set up data store*/
var data = {
identifier: "id",
items: [{
id : 1,
col2 : "aa",
col3 : "bb",
col4 : "cC"
}]
};
var store = new ItemFileWriteStore({
data: data
});
/*set up layout*/
var layout = [
[{
'name': 'Column 1',singleClickEdit:'true', editable:'true',
'field': 'id',
'width': '100px'
}, {
'name': 'Column 2',singleClickEdit:'true', editable:'true',
'field': 'col2',
'width': '100px'
}, {
'name': 'Column 3',singleClickEdit:'true', editable:'true',
'field': 'col3',
'width': '200px'
}, {
'name': 'Column 4',formatter: updateDetails,
'field': 'col4',
'width': '150px'
}]
];
/*create a new grid*/
var grid = new EnhancedGrid({
id: 'grid',
store: store,
structure: layout,
sortInfo: -1,
});
/*append the new grid to the div*/
grid.placeAt("gridDiv");
/*Call startup() to render the grid*/
grid.startup();
aspect.after(grid, 'renderRow', grid.sort);
var id = 2;
var button = new Button({
onClick: function () {
console.log(arguments);
store.newItem({
id: id,
col2: "col2-" + id,
col3: "col3-" + id,
col4: "col4-" + id
});
id++;
}
}, "addRow");
});
var updateDetails = function(value, rowIndex) {
var col2 = this.grid.getItem(rowIndex).col2;
alert("col2 updated value : " + col2);
return "<a href=\"<%=request.getContextPath()%>/updateInfo.htm?col2="+col2 +"\">" + "UPDATE";
};
spring controller code:
#RequestMapping(value = "/updateInfo", method = RequestMethod.GET)
public ModelAndView updateInfo(HttpServletRequest request,
HttpServletResponse response, #ModelAttribute MyDTO myDto,
#RequestParam("col2") String col2, #RequestParam("col2") String col2){
System.out.println("col2 value: " + col2);
System.out.println("col3 value: " + col3);
//when i type some value in COlumn2/Column3 of enhanced grid and column is still in edit mode then on click of UPDATE , new value is not passed to spring controller, its passing the old value.
...
...
//logic to save in DB
}
This line:
return "<a href=\"<%=request.getContextPath()%>/updateInfo.htm?col2="+col2 +"\">" + "UPDATE";
is returning an anchor with the href as "/contextPath/updateInfo.html?col2=aa". That renders it and that's it; that URL is never changing. Then, when you click on UPDATE, it sends what was in there when the page was rendered, not what the current value in your table is.
If you want to have the current value be sent, you should have your href be "#" and have an onclick="updateValue(1)" like this:
UPDATE
where 1 is the row number.
Then, in your update value function, you'd send an ajax request to update the value. Since you're using dojo, check this out: http://dojotoolkit.org/documentation/tutorials/1.8/ajax/
Here's what your function might look like (some pseudo code, some comments to describe behavior):
function updateValue(rowNum){
//var row = data.items.getRow(rowNum); or something like this
//Call ajax here and send the new row values
}
After messing with dojo for about an hour, and struggling with dojo's scoping and how to call a function that has access to the data grid and/or it's data store (sorry..I had 0 experience with dojo before this question)...here's your easy way out, OP:
http://jsfiddle.net/hm8gpz6o/
The important parts:
EnhancedGrid was NOT re-rendering the formatter generated cell when your data store was updated. This seems like a problem with dojo's EnhancedGrid.
I added the following (onApplyCellEdit will fire when a cell is updated):
/*create a new grid*/
var grid = new EnhancedGrid({
id: 'grid',
store: store,
structure: layout,
sortInfo: -1,
onApplyCellEdit: function(inValue, inRowIndex, inFieldIndex){
refreshGrid();
}
});
And finally, refreshGrid() will force a re-render of the whole grid. I hate that I have to do this:
function refreshGrid(){
grid.startup();
}
Please see the fiddle for the full working example.

How to define a Kendo grid Column filter between two dates?

In our application we want the filter on a date column to prompt the user for a start date and an end date, with the filter returning rows where the field in question falls between (or on) those two dates.
Initial Approach
Our initial approach was to restrict date types to use gte and lte operators, and add the "extra : true" filterable option on the column. This came close, but presented the following problems: A) Each date input could use either the gte (Start) or lte (End) operator, providing undesired flexibility and the option for the user to create a filter that would never return results, and B) Presented a logical comparison (And / Or) that we don't want.
Better Approach
This question has an answer by Matthew Erwin that gets us very close: it allows us to completely re-style the filter entirely, so we can present simply a Start Date input and an End date input. However, what I can't get working is associating the right filter operation with the right input (gte for the Start date, lte for the End date). My custom filter is as follows:
$scope.dateFilter = {
extra: true,
operators: {},
ui: function (element) {
var parent = element.parent();
while (parent.children().length > 1)
$(parent.children()[0]).remove();
parent.prepend(
"Start Date:<br/><span class=\"k-widget k-datepicker k-header\">" +
"<span class=\"k-picker-wrap k-state-default\">" +
"<input data-bind=\"value: filters[0].value\" class=\"k-input\" type=\"text\" data-role=\"datepicker\"" +
" style=\"width: 100%\" role=\"textbox\" aria-haspopup=\"true\" aria-expanded=\"false\" aria-disabled=\"false\" " +
" aria-readonly=\"false\" aria-label=\"Choose a date\">" +
"<span unselectable=\"on\" class=\"k-select\" role=\"button\">" +
"<span unselectable=\"on\" class=\"k-icon k-i-calendar\">select</span></span></span></span>" +
"<br/>End Date:<br/>" +
"<span class=\"k-widget k-datepicker k-header\"><span class=\"k-picker-wrap k-state-default\">" +
"<input data-bind=\"value: filters[1].value\" class=\"k-input\" type=\"text\" data-role=\"datepicker\"" +
" style=\"width: 100%\" role=\"textbox\" aria-haspopup=\"true\" aria-expanded=\"false\" " +
" aria-disabled=\"false\" aria-readonly=\"false\" aria-label=\"Choose a date\">" +
"<span unselectable=\"on\" class=\"k-select\" role=\"button\">" +
"<span unselectable=\"on\" class=\"k-icon k-i-calendar\">select</span></span></span></span>"
);
}
};
With this approach, the Odata filter option is generated for each of the dates, however it uses the eq Equal To operator, so no values are ever returned. We aren't building filters specifically on the data source.
Is there a simple way I can associate each of those date inputs with a specific filter operator? Is there a better way to approach this subject? It seems like filtering dates based on a Start - End range would be commonly desired.
Other Details
We are using AngularJS, and WebAPI with Odata.
After working with Telerik, I came to an answer. The thread that I opened can be found here, but I'll also summarize in this answer.
The ultimate solution was to:
Use the "Messages" option of the column "filterable" option to customize the filter display message.
Use the "Extra" option of the column "filterable" option to get the extra Date selector in the filter menu.
Configure the "Operators" option in the grid filterable option to set what operators can be used for dates (gte, lte) and what text is displayed for each (Begin Date, End Date).
Use the filterMenuInit event to configure the filter controls.
End Result
Column Filterable
The following filterable options were used:
filterable: { "extra": "true", "messages": { "info": "Show items between dates:" }}
Extra gives us the second date selector, and the "info" message customizes the text displayed at the top of the filter menu.
Grid Filterable
I used the "operators" option in the grid-level "filterable" option to make date filters only provide the gte and lte operators, and to customize the text for those operators. This is what the operators configuration object wound up looking like:
"date": {
"gte": "Begin Date",
"lte": "End Date"
}
Because we want this to apply for all dates, we put that in a factory and reuse it in each angular controller / view.
filterMenuInit Event
By providing a handler for the filterMenuInit event, you can access and configure the individual controls in the filter menu as it is created. The handler function that I created looks like this:
function (e) {
if (e.sender.dataSource.options.schema.model.fields[e.field].type == "date") {
var beginOperator = e.container.find("[data-role=dropdownlist]:eq(0)").data("kendoDropDownList");
beginOperator.value("gte");
beginOperator.trigger("change");
beginOperator.readonly();
var logicOperator = e.container.find("[data-role=dropdownlist]:eq(1)").data("kendoDropDownList");
logicOperator.readonly();
var endOperator = e.container.find("[data-role=dropdownlist]:eq(2)").data("kendoDropDownList");
endOperator.value("lte");
endOperator.trigger("change");
beginOperator.readonly();
}
Specifically, for any date field, this function sets the first and last dropdown operators to "gte" and "lte" respectfully (Those are the dropdowns for the first date operator and the second date operator), and sets all of the dropdowns to read-only so the user can't change them (the only other dropdown, which is at index 1, is the logical comparison - only And makes sense, so we don't let users change it.)
This function applies this configuration for any fields that are of "date" type. I did it this way so that I could create this function once, put it in an Angular factory, and then reuse it for any grid that I needed. If you don't want to apply this as a blanket configuration across all of your date columns, you can change the conditional to check for fields by name. Example:
if (e.field == "fieldName")
Hopefully this will be helpful to someone else. This doesn't give you ultimate customization of the UI in the filter menu, but it does let you simply set up a filter between two dates. I'm sure someone clever could merge this with my original strategy (replacing the markup for the filter menu entirely) to come up with something completely customized.
You can try the following method that gives two option for filtering: With two filtering fields and with the grid column.
<div>
From: <input id="from" /> To: <input id="to" />
<br />
<br />
<button id="filter" class="k-button">Filter</button>
</div>
<br />
<br />
<div id="grid"></div>
<script>
var grid = $("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: "/Controller/Action"
},
pageSize: 10,
schema: {
model: {
fields: {
OrderId: { type: 'number' },
OrderItem: { type: 'string' },
OrderDate: { type: 'date' }
}
}
}
},
pageable: true,
filterable: true,
navigatable: true,
selectable: true,
columns:
[
{ field: "OrderID", width: 100, title: "Order ID", filterable: false },
{ field: "OrderItem", width: 100, title: "Order Item", filterable: false },
{
field: "OrderDate", type: "date", width: 125, title: "Order Date",
template: "#= kendo.toString(kendo.parseDate(EventTime, 'dd.MM.yyyy hh:mm tt'), 'dd.MM.yyyy hh:mm tt') #",
filterable: {
ui: "datetimepicker"
}
},
]
}).data("kendoGrid");
$("#from, #to").kendoDatePicker({
});
$("#filter").on("click", function () {
//var from = $("#from").data("kendoDatePicker").value();
//var to = $("#to").data("kendoDatePicker").value();
//If there is a problem regarding to the two lines above, you can also try this:
var from = $("#from").val();
var to = $("#to").val();
var filter = [
{ field: "OrderDate", operator: "gte", value: from },
{ field: "OrderDate", operator: "lte", value: to }
];
grid.dataSource.filter(filter);
});
</script>
For more information Date Range Filtering in Kendo Grid Using WEB API and Entity Framework.

How to add a new row in a group in jqGrid?

I am totally new to jqGrid. I am populating the grid from an array with datatype:local.
var data=[
{date : "01/01/2012",starttime:"10:15",endtime:"11:15",workfunction:"MA"},
{date : "01/02/2012",starttime:"11:30",endtime:"12:30",workfunction:"CA"},
{date : "01/03/2012",starttime:"13:30",endtime:"14:30",workfunction:"FC"},
{date : "01/01/2012",starttime:"10:15",endtime:"11:15",workfunction:"MA"},
{date : "01/01/2012",starttime:"11:30",endtime:"12:30",workfunction:"CA"},
{date : "01/02/2012",starttime:"13:30",endtime:"14:30",workfunction:"FC"},
{date : "01/02/2012",starttime:"10:15",endtime:"11:15",workfunction:"MA"},
{date : "01/03/2012",starttime:"11:30",endtime:"12:30",workfunction:"CA"},
{date : "01/03/2012",starttime:"13:30",endtime:"14:30",workfunction:"FC"}
];
$("#gridTable").jqGrid({
data : data,
editurl:"clientArray",
datatype: "local",
height : 250,
colNames: [' ','Date','Start Time','End Time','Work Function'],
colModel : [
{name: 'myac', width:80, fixed:true, sortable:false, resize:false, formatter:'actions',formatoptions:{keys:true}},
{name: 'date',index:'date',width: 100,sorttype:'date',editable:true,editoptions : {
dataInit : function(element){
formatDatepicker(element,data);
}
}},
{name: 'starttime',index:'starttime',width: 100,sorttype:'date',editable:true},
{name: 'endtime',index:'endtime',width: 100,sorttype:'date',editable:true},
{name: 'workfunction',index:'workfunction',width: 100,sorttype:'date',editable:true,edittype:"select",editoptions:{value:"MA:MA;CA:CA;FC:FC"}},
],
pager: "#gridPager",
caption : "Weekly Details",
grouping : true,
groupingView : {
groupField:['date']
}
}).navGrid("#gridPager",{edit:true,add:true,del:false},
//edit properties
{
zIndex : 950,
}
);
Given above is the grid I am using. I am grouping the grid according to dates, and I am using jsp as the server side technology. My questions are:
Can we add a row to a group without submitting it to the server.
When a new row is created with a new date, will a new group form.
Can we edit multiple rows and submit all at once.
let me be sure if i understood you right...1. you want to add a row to grid but dont want to submit the data to server? it is possible...2. you have to be more clear on this requirement. 3. yes it is possible to take all the edit data of multiple rows and send the data to server.
I'll start with 3.
you can use multiselect: true here, its like the easiest option. Select the rows which you want to edit and Implement onSelectRow with a function which will make your rows editable on selecting them.
and then you can have a button which will take your edited rows data to server.
how to make rows editable on selecting them
onSelectRow: function(id){
jQuery('#grid').editRow(id, true); }
or there's another alternative keep your all rows in editable mode
gridComplete:OnGridComplete, //add this to your Jqgrid parameters
javascript function
function OnGridComplete(){
var $this = $(this), rows = this.rows, l = rows.length, i, row;
for (i = 0; i < l; i++) {
row = rows[i];
if ($.inArray('jqgrow', row.className.split(' ')) >= 0) {
$this.jqGrid('editRow', row.id, true);
}
}
}
and how to take edited data to server just on one click, see my answer
https://stackoverflow.com/a/11662959/1374763
and now with you first question
you should change the editUrl to clientarray,
jQuery("#grid_id").jqGrid('saveRow',"rowid", false, 'clientArray');
check this link and go to saveRow parametrs, for more info
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing

Categories

Resources