I have a jqgrid with multiselect true and I want to set some of rows.(I know the row ids.) How can I do that?
I mean opposite of
$("#myTable").jqGrid('getGridParam', 'selarrrow');
as like:
$("#myTable").jqGrid('setGridParam', 'selarrrow', rowArray);
You have to loop through the rowArray array and call setSelection method for every rowid from the rowArray:
var i, count, $grid = $("#myTable");
for (i = 0, count = rowArray.length; i < count; i += 1) {
$grid.jqGrid('setSelection', rowArray[i], false);
}
$.each(rowsToSelect, function(_, rowId) {
$grid.setSelection(rowId, false);
});
No much difference. Just seemed neater :)
(Pretty amazing that even now, in 2014, jqGrid doesn't persist checkboxes when paging..)
Here's the code I needed to use, with jqGrid 4.4.5, to get the checkboxes to set, after moving to a new page:
var idsOfSelectedRows = []; // list of RowIDs for rows which have been ticked
$("#tblContracts").jqGrid({
...
colModel: [
{ name: 'AddContract', width: 50, align: "center", editable: true, edittype: 'checkbox', editoptions: { value: "True:False" }, formatter: "checkbox", formatoptions: { disabled: false } },
{ name: "ContractName", search: true, width: 80, align: "center" }
],
loadComplete: function () {
for (i = 0; i < idsOfSelectedRows.length; i++) {
$(this).setCell(idsOfSelectedRows[i], 'AddContract', true);
}
},
During development, I put an "alert" in that "for" loop. I found that using "setSelection" simply stepped through my list of RowIDs, selected the row (so it would become highlighted), then moved on to the next, selecting that one instead.
It didn't ever tick any of the checkboxes.
Notice that my "setCell" function includes the name of the jqGrid column where I have a checkbox.
If you cut'n'paste this code, make sure you change this line to reflect the name of your jqGrid checkbox column.
Related
i am trying to highlight the cells in Red whichever values not matching with my predefined values
and
1. i want to get the count of red cells in each row in the column Error_cells_Count,now in the demo page i have manually entered the count
2. and i want to prevent user from selecting the dropdown in status column if the row has any red cells.
i have managed to highlight the cells.
please help to get the red cells count in Error_cells_Count column and prevent user from selecting dropdown.
this is my demo page http://jsfiddle.net/h8Lzgh7d/27/
Jqgrid version version is 4.14.0
and also kindly suggest if any possibilities to have predefined dictionary and correct the red cells automatically by replacing the red cell values with dictionary value
First of all I'd recommend you to use cellattr to set any CSS properties on the cell. Seconds you can use editable defined as function to allow editing the cell depend on some your custom criteria (see the wiki article for more details).
The fixed demo could be the following https://jsfiddle.net/OlegKi/h8Lzgh7d/30/. It uses the following code:
var hilightcolorcell=["PURPLE","PINK","GREEN"];
var hilightcahractercell=["Character 1","Character 2","Character 3"];
jQuery("#rowed5").jqGrid({
datatype: "local",
shrinkToFit: false,
data: mydata,
height: 320,
autowidth:true,
colNames:['RowID','Error_Cells_Count','status','note','color_name','character_name','Variant ID'],
colModel: [
{name:'id', width:55, sorttype:"int",align:"center",frozen:true},
{name:'Error_Cells_Count', width:100, sorttype:"int",
align:"center",frozen:true,
cellattr: function (rowid, cellValue) {
if (cellValue != null) {
var value = parseInt(cellValue, 10);
return " class='" +
(value > 0 ? "redcells" : "greencells") +
"'";
}
}},
{name:'status', width:100,
editable: function (options) {
var item = $(this).jqGrid("getLocalRow", options.rowid);
return (item.Error_Cells_Count == null || item.Error_Cells_Count <= 0) &&
$.inArray(item.color_name, hilightcolorcell) >= 0 &&
$.inArray(item.character_name, hilightcahractercell) >= 0;
},
edittype:"select",editoptions:{value:"Approve:Approve"}},
{name:'note',width:100, sortable:false,editable: true,
edittype:"textarea", editoptions:{rows:"2",cols:"10"}},
{name:'color_name',
cellattr: function (rowid, cellValue) {
if ($.inArray(cellValue, hilightcolorcell) < 0) {
return " class='redcells'";
}
}},
{name:'character_name',
cellattr: function (rowid, cellValue) {
if ($.inArray(cellValue, hilightcahractercell) < 0) {
return " class='redcells'";
}
}},
{name:'v_id'}
],
cmTemplate: { width:110 }, // define default properties for colModel
editurl: "functions.php",
cellEdit: true,
cellsubmit: 'remote',
cellurl: 'functions.php',
searching: {
stringResult: true,
searchOnEnter: false,
defaultSearch : "cn"
}
}).jqGrid("setFrozenColumns")
.jqGrid("filterToolbar");
I'm using jquery.jqgrid version v4.4.4, mvc 5.
In my inline jqgrid, i have Phone Number colModel need to be mask in US Phone number format and my code looks like,
{
name: 'PhoneNumber', index: 'PhoneNumber', editable: true, sortable: true, width: 300, classes: "grid-col",
editoptions: { dataInit: function (elem) {
$(elem).mask("?(999) 999-9999");
$(this).val(elem);
}
}
},
If i type like this'(454)453-3233' the field(textbox) holds the correct value and get saved as '4544533233' in database correctly. To remove the brackets and hypen i used,
PhoneNumber = PhoneNumber.replace(/\D/g, ''); //Removes anything that is not a digit \D
The issue is,
First,if i type like this '( 54)4 - 65' then the field formatted itself and holds (544)65 which is wrong.
Second, the existing phone numbers are not masked, displays in the grid without mask format.
1).How to make the field to hold and save the input with same position as i typed?
2).How to display the existing Phone Number('4544533233'stored like this in db) in mask format?
Thanks.
colModel[{ name: 'DOB', width: 75, editable: true, formatter: dateFormatter, editoptions: { class: 'isDateField' } }]
//dateFormatter function to format before saving
function dateFormatter(cellvalue, options, rowObject) {
if (cellvalue !== undefined) {
var formattedValue = (cellvalue.slice(0, 4) + '/' + cellvalue.slice(4, 6) + '/' + cellvalue.slice(6, 8));
if (formattedValue==='//') {
return ('');
}
return formattedValue;
}
};
I want to add a column which will contain summation of some columns.
Basically I want to convert following:
to the following:
But this has to be done dynamically i.e. I shall provide colModel id of th e columns I want the summation of.
P.S. Using 4.13.5 version of free-jqgrid.
The most easy way to implement your requirements would be the usage of jsonmap and sorttype defined as function, which returns the calculated value of the column. Additionally you would need to implement afterSetRow callback, which fixes the value after modification the row (after setRowData).
The corresponding implementation could be like in the demo. The demo defines the grid with total column, which displays the sum of amount and tax columns. The code of the demo looks as following:
var calculateTotal = function (item) {
return parseFloat(item.amount) + parseFloat(item.tax);
};
$("#list").jqGrid({
...
colModel: [
...
{ name: "amount", template: "number", ... },
{ name: "tax", template: "number", ... },
{ name: "total", width: 76, template: "number", editable: false,
jsonmap: function (item) {
return calculateTotal(item);
},
sorttype: function (cellValue, item) {
return calculateTotal(item);
}},
...
],
afterSetRow: function (options) {
var item = options.inputData;
if (item.total === undefined) {
// test is required to prevent recursion
$(this).jqGrid("setRowData", options.rowid, {
total: calculateTotal(item)
});
}
}
...
});
how can I make one single cell editable out of a not editable column?
my javaScript looks like this:
$( '#grid' ).jqGrid({
// ...
cellEdit : true,
colModel : [
{ name : "id", index : "id", editable : false },
{ name : "wbs", index : "wbs", editable : false },
{ name : "value", index : "value", editable : false }
],
loadComplete : function(data) {
// ... foreach ( cell in data.rows.columns ) ...
if ( cell.shouldBeEditable ) {
jQuery('#grid').setCell(cell.row, cell.col, '', 'green', { editable : true });
}
}
// ...
}
so, after globally setting columns as not editable, I try to set them as editable locally, based on some criteria (to identify them more easily I also paint them green).
Alas, it's not working: cells become green, but when I try to click them they do not become editable.
Inspecting the selected cell with firebug reveals the edit-cell class to be correctly applied.
As a last note, it's working if I set columns as editable in the first instance.
I suggest you do it in reverse. Make the column editable, but disable the cells that you do not want to be editable. This is a function I wrote to disable cells:
// cellName is the name defined in your colModel
function disableGridCell(cellName) {
var cell = $('[name="' + cellName + '"]');
cell.css('display', 'none');
var div = $("<div>")
.css('width', '100%')
.css('height', '100%')
.css('border', '1px solid #000')
.css('background-color', '#CCC')
.text('xxxxxxxxxxxx');
cell.parent().append(div);
}
I call disableGridCell inside of my onEditFunc of my grid's editRow function:
$('#grid').jqGrid('editRow', id, keys, onEditFunc);
function onEditFunc(id) {
if (condition to disable cell) {
disableGridCell('CellName');
}
}
I found a nice workaround to the problem (thanks to Walter for getting me on the right track).
Instead of locking all the cells and selectively unlocking them in a declarative manner (which may lead to long load times), I'm declaring all the cells as editable.
Then I'm attaching a callback to afterEditCell option:
var $grid = $('#grid');
$grid.jqGrid({
// ...
afterEditCell : function(rowid, cellname, value, iRow, iCol) {
if ( shouldNotBeEditable(iRow, iCol) ) {
$grid.setCell(rowid, cellname, '', 'not-editable-cell');
$grid.restoreCell(iRow, iCol);
}
},
// ...
});
This way the cell is immediately reset to its previous value and I ensure that the callback gets called only once per not-to-be-edited cell, since the cell is made into a not-editable-cell after the first call.
colModel:[
{name:'description',index:'description', width:4, sortable: false, editable: true},
{name:'qty',index:'qty', width:1,sortable: false, editable: true},
{name:'cost',index:'cost', width:1, editable: true, sortable: false},
{name:'totalCost',index:'totalCost', width:1, sortable: false}
onCellSelect: function(rowid, iCol, cellcontent, e) {
//here it will allow editing of either qty or cost col for that rowid
//only if both cols have a numeric value already
if(iCol===1 || iCol===2) {
var rowdata = $("#projectTable").getRowData(rowid);
var itemCost = parseInt(rowdata['cost']);
var qty = parseInt(rowdata['qty']);
if(!$.isNumeric(itemCost) || !$.isNumeric(qty)) {
$("#projectTable").jqGrid('setColProp','qty',{editable: false});
$("#projectTable").jqGrid('setColProp','cost',{editable: false});
} else {
$("#projectTable").jqGrid('setColProp','qty',{editable: true});
$("#projectTable").jqGrid('setColProp','cost',{editable: true});
}
}
},
In my jqgrid when i am clicking on add new record i have date field prepopulated with current date. Format of the date is yyyy-MMM-d (e.g. 2010-Jan-23).
Date is required field and when i click submit button it fails validation and displays error that this date is invalid, and it wants Y-m-d format.
How can i check my value with jqgrid? In other words how to make jqgrid accept the following date format when validating 2010-Jan-23?
Thanks.
Here is my JSON data:
{"rows":[
{"id":1,"cell":["2010-Mar-3","Pepto","2","False","not active"]},
{"id":2,"cell":["2009-May-6","Tylenol","5","False","not active"]},
{"id":3,"cell":["2008-May-6","Aspirin","9","True","active"]}
]}},
Here is my date column definition:
{ name: 'Date',
index: 'date',
width: '80px',
align: 'center',
sortable: false,
editable: true,
datefmt: 'Y-M-d',
editoptions: { dataInit: function(elem) { $(elem).datepicker({ dateFormat: 'yy-M-d' });},value: getDate } ,
editrules: { required: true, date:true} },
The getdate function inserts current date into field. here is the function:
function getDate(){
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var now = new Date();
return now.getFullYear() + "-" + monthNames[now.getMonth()] + "-" + now.getDate();
}
Maybe this is because of this function? Can i insert current date from datepicker?
Amount of data sent from the server is not too big (about 10-30 rows) and this application will be used by maximum of 50 people, so there is no concerns regarding amounts of data.
Anytime when i have value as 2010-Jun-23 in the field, i get error message:Enter valid date value - Y-M-d
Verify that you defined datefmt: 'Y-M-d' in the column definition of colModel. In the list of editrules options (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules#editrules) is defined that if you use date: true as a editrules option, the validation will be done corresponds with the datefmt option.
Some more recommendations if you use date in jqGrid:
If you not yet use, think about of the usage of jQuery.datepicker (see http://jqueryui.com/demos/datepicker/#date-formats) inside of dataInit function of editoptions (like
editoptions: {
dataInit : function (elem) {
$(elem).datepicker();
}
// ...
}
in the simplest case). If you use searching for date fields, you can use dataInit with jQuery.datepicker also in searchoptions in the same way (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:singe_searching#colmodel_options). The usage of jQuery.datepicker in jqGrid is very easy, but it makes your program more comfortable.
Usage of standard date formatter (formatter: 'date') can be useful to convert source data format send to jqGrid to the new format which will be displayed. For example,
formatter: 'date', formatoptions: {srcformat:'y-m-d', newformat: 'Y-M-d' }
It is less interesting, but it can reduce a little the size of data send from server to client.
UPDATED: I must admit, I don't tested my suggestion with exactly your data format. Just now I tested all one more time and then read carefully jqGrid documentation about datefmt (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options). For datefmt are only numerical format for months is supported! So the value at the time of date verification must be in a numerical format. What can we do? For example following
we define as parameters of navGrid function "add" parameters (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:navigator parameter prmAdd) like following:
{ beforeCheckValues: function(posdata, formid, mode) {
var data = posdata.Date;
var dateParts = data.split("-");
var mounth = dateParts[1];
var mounths = $.jgrid.formatter.date.monthNames;
var iMounth = -1;
for (var i=0; i<12; i++) {
if (mounth === mounths[i]) {
iMounth = i;
break;
}
}
if (iMounth !== -1) {
posdata.Date = dateParts[0]+'-'+(iMounth+1)+'-'+dateParts[2];
}
},
beforeSubmit: function(postdata, formid) {
var data = postdata.Date;
var dateParts = data.split("-");
var mounths = $.jgrid.formatter.date.monthNames;
postdata.Date = dateParts[0]+'-'+
$.jgrid.formatter.date.monthNames[dateParts[1]-1]+
'-'+dateParts[2];
return [true,""];
}
}
So we convert the Date field to the numerical format inside of beforeCheckValues function and then convert all back to the original format (like 2010-Jan-23) after usage of checkDate. It will work.
The main question is now: have we some advantage from such kind of the date checking? We can just don't use editrules: { date:true } and implement our own date checking inside of beforeSubmit function. If we find out the wrong date we should return [false,"My error message"] and our custom error message "My error message" will be displayed by jqGrid.
So the easiest solution of your problem we receive if we could change the date format to any numerical form (Y-mm-d, mm/d/Y or another one). Usage of datepicker will makes for users the format problem not very important. Think about this and choose the way which your prefer.
I was facing similar issue. I have resolved it using custom function for validation. I am suing date format as '23-Jan-05'. You may modify it to suit your required date format.
function datecheck(value, colname) {
var dateParts = value.split("-");
var datePart = dateParts[0];
var mounth = dateParts[1];
var yearPart = dateParts[2];
var mounths = $.jgrid.formatter.date.monthNames;
var monthPart = -1;
for (var i = 0; i < 12; i++) {
if (mounth === mounths[i]) {
monthPart = i + 1;
break;
}
}
var dateText = monthPart + '-' + datePart + '-' + yearPart;
var date = Date.parse(dateText);
if (isNaN(date))
return [false,"Invalid date. Format expected: dd-mmm-yy. (23-Jul-05)"];
else
return [true,""];
}
JQGrid column details:
colModel: [name: 'JoiningDate', align: "center", editable: true,
editrules: { custom: true, custom_func: datecheck },
formatter: 'date', formatoptions: { srcformat: 'y-m-d', newformat: 'd-M-y' }, edittype: 'text', editable: true,
editoptions: { dataInit: function (el) { setTimeout(function () { $(el).datepicker({ dateFormat: 'd-M-y' }); }, 200); } }
},
Hope this helps.
Regards,
Abhilash