How to resize JqGrid column width - javascript

net webform using jqGrid with column Action, Responsible, Target date.
How can i resize the columns. i try to add width:'116' on the column but did not work
i don't have any error on my console
my grid looks like this opon adding
Grid looks
Here's my code on jqgrid
function loadActions(datas) {
// var Responsible = Responsible(),
// Refresh data if jqgrid is already initialized
$('#Actiongrid').jqGrid("GridUnload");
$('#Actiongrid').jqGrid('clearGridData').trigger("reloadGrid");
$('#Actiongrid').jqGrid({
datatype: 'local',
data: datas,
editurl: 'clientArray',
colNames: ['Action','Responsible','TargetDate'],
colModel: [
{ name: 'Batch_no', index: 'Batch_no', sortable: false, editable: true, width:'116' },
{
name: 'Responsible',
index: 'Responsible',
width: '116',
sortable: false,
editable: true,
editrules: { required: true },
edittype: 'select',
editoptions: { value: {} },
},
{
name: 'TargetDate',
width: '116',
index: 'TargetDate',
sortable: false,
editrules: {
required: true,
date: true
},
editable: true,
width: '70px',
align: 'center',
editoptions: {
dataInit: function (el) {
$(el).datepicker({ dateFormat: 'yy-mm-dd' });
},
defaultValue: function () {
var currentTime = new Date();
var month = parseInt(currentTime.getMonth() + 1);
month = month <= 9 ? "0" + month : month;
var day = currentTime.getDate();
day = day <= 9 ? "0" + day : day;
var year = currentTime.getFullYear();
return year + "-" + month + "-" + day;
}
}
},
],
// beforeSelectRow: function (id) {
// if ($('#' + id).attr('editable') == 1) {
// return false;
// }
// },
pager: '#Actiongridpager',
pgbuttons: false,
pginput: false,
sortorder: 'asc',
sortname: 'name',
multiselect: true,
height: '100',
maxheight: '100',
width: '350',
viewrecords: true,
rowNum: 10000
});
$('#Actiongrid').jqGrid({ recreateForm: true })
// Disable form CRUD
$('#Actiongrid').jqGrid('navGrid', '#Actiongridpager', { edit: false, save: false, add: false, cancel: false, del: true, search: false, refresh: false });
// Enable inline CRUD
$('#Actiongrid').jqGrid('inlineNav', '#Actiongridpager', { add: true, edit: true, save: true, cancel: true });
}
What i'm doing wrong or what do i need to add . Hope some help me out with this.
Thank you in advance.

Related

jqGrid update dropdown options based on first selected dropdown Edit mode

I have a jqGrid that loads fine and the drop down loads fine as well but I'm not sure hot to go about updating(loading) the second dropdown based on the first dropdown's onchange event.
Here is my grid. As you can see I load countries but now I would like to load the available currencies based on the selected country.
$("#jqgrid").jqGrid
({
url: '#Url.Action("GetSupplierData", "Maintenance")',
datatype: 'json',
mtype: 'Get',
//table header name
colNames: [
'Id', 'Code', 'Name', 'Account Number', 'Contact Person', 'Contact Number',
'Email', 'Address', 'Country', 'Currency', 'InsertUserId',
'InsertDateTime', 'InsertUserName', 'UpdateUserId', 'UpdateDateTime', 'UpdateUserName'
],
//colModel takes the data from controller and binds to grid
colModel: [
{
key: true,
hidden: true,
name: 'id',
index: 'id',
editable: true
}, {
key: false,
name: 'code',
index: 'code',
editable: true
}, {
key: false,
name: 'name',
index: 'name',
editable: true
}, {
key: false,
name: 'accountnumber',
index: 'accountnumber',
editable: true
}, {
key: false,
name: 'contactperson',
index: 'contactperson',
editable: true
}, {
key: false,
name: 'contactnumber',
index: 'contactnumber',
editable: true
}, {
key: false,
name: 'email',
index: 'email',
editable: true
}, {
key: false,
name: 'address',
index: 'address',
editable: true
}, {
key: false,
name: 'countryId',
index: 'countryId',
editable: true,
edittype: 'select',
editoptions: {
dataInit: function(element) {
$.ajax({
url: '#Url.Action("GetCountries", "Maintenance")',
dataType: 'json',
type: 'POST',
success: function(response) {
var array = response;
if (array != null) {
var i;
for (i in array) {
if (array.hasOwnProperty(i)) {
if (ctyId == array[i].id) {
$(element).append("<option value=" + array[i].id +" selected>" + array[i].name +"</option>");
} else {
$(element).append("<option value=" + array[i].id + ">" + array[i].name + "</option>");
}
}
}
}
}
});
},
dataEvents:
{
type: 'change',
fn: function (e) {
}
}
},
editrules: { required: true, integer: true }
}, {
key: false,
name: 'currencyId',
index: 'currencyId',
editable: true
}, {
key: false,
hidden: true,
name: 'insertUserId',
index: 'insertUserId',
editable: true
}, {
key: false,
hidden: true,
name: 'insertDateTime',
index: 'insertDateTime',
editable: true
}, {
key: false,
hidden: true,
name: 'insertUserName',
index: 'insertUserName',
editable: true
}, {
key: false,
hidden: true,
name: 'updateUserId',
index: 'updateUserId',
editable: true
}, {
key: false,
hidden: true,
name: 'updateDateTime',
index: 'updateDateTime',
editable: true
}, {
key: false,
hidden: true,
name: 'updateUserName',
index: 'updateUserName',
editable: true
}
],
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
caption: 'Suppliers',
emptyrecords: 'No records to display',
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
pager: '#pjqgrid',
sortname: 'id',
toolbarfilter: true,
viewrecords: true,
sortorder: "asc",
autowidth: true,
multiselect: false,
onSelectRow: function(id) {
var selRowId = $("#jqgrid").jqGrid('getGridParam', 'selrow');
ctyId = $("#jqgrid").jqGrid('getCell', selRowId, 'currencyId');
}
//pager-you have to choose here what icons should appear at the bottom
//like edit,create,delete icons
}).navGrid('#pjqgrid',
{
edit: true,
add: false,
del: true,
search: true,
refresh: true
},
{
// edit options
zIndex: 1000,
url: '#Url.Action("EditSupplier", "Maintenance")',
dataType: "html",
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function(response) {
$('#alerts').html(response.responseText);
}
},
{
// add options
},
{
// delete options
zIndex: 1000,
url: '#Url.Action("DeleteSupplier", "Maintenance")',
type: "POST",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
msg: "Are you sure you want to delete this?",
afterComplete: function(response) {
$('#alerts').html(response.responseText);
}
});
This Guriddo of jqGrid example will point you in the right direction.

JqGrid give ID when button pressed

I cant select any rows in my JqGrid so I came across http://www.jqgrid.com/jqgrid/forum/codemerx-jqgrid-for-asp-net/146-can-t-select-rows. Which says I need a ID for every row. I add data to my Grid each time I press a button. I tried giving each row a id with a simple click counter function. But then I when I try to sort all ID's dissapear from the Grid.
Any suggestion how I can solve this?
Grid
$(document).ready(function () {
// Configuration for jqGrid Example 1
$("#table_list_1").jqGrid({
data: currentTime,
datatype: "local", //if enabled id dissapear
height: "100%",
autowidth: true,
shrinkToFit: true,
loadonce: true,
sortable: true,
rowNum: 100,
rownumbers: true,
rowList: [10, 20, 30],
colNames: ['Id','Time', 'Note'], // 'Id'
colModel: [
{name: 'id', index:'id', width:60, sorttype: 'number', sortable: true},
{ name: 'time', index: 'time', width: 60, sorttype: 'number', sortable: true, editable: true, formatter: "number" },
{ name: 'note', index: 'note', width: 60, cellEdit: true, editable: true }
],
pager: "#pager_list_1",
viewrecords: true,
caption: "Example jqGrid 1",
add: true,
edit: true,
addtext: 'Add',
edittext: 'Edit',
hidegrid: false
});
$('#table_list_1').navGrid('#pager_list_1',
{ edit: false, add: false, del: false, search: true, refresh: true, view: false, position: "left", cloneToTop: true },
{ reloadAfterSubmit: true });
$('#table_list_1').navButtonAdd('#pager_list_1',
{
buttonicon: "ui-icon-pencil",
title: "Edit",
caption: "",
position: "last",
});
How I add data
var currentTime = [];
var id = 0;
function doKeyDown(e) {
//test document.getElementById("currentTimeText").innerHTML = currentTime;
if (e.keyCode == 49 & wavesurfer.isPlaying()) {
// KEY = " 1 "
id += 1;
currentTime.push(wavesurfer.getCurrentTime());
jQuery("#table_list_1").addRowData("", { id: id, time: wavesurfer.getCurrentTime() });
//test document.getElementById("currentTimeText").innerHTML = currentTime;
wavesurfer.addRegion({
start: wavesurfer.getCurrentTime(),
end: wavesurfer.getCurrentTime() + 0.1,
color: '#19aa8d',
resize: false,
drag: false,
});
}
}
The rowid is not the value from id property, but the first parameter which you use with the same "" value. I think it's the main bug in your code. The call
jQuery("#table_list_1").addRowData("", { id: id, time: wavesurfer.getCurrentTime() });
should be fixed at least to
jQuery("#table_list_1").addRowData(undefined, { id: id, time: wavesurfer.getCurrentTime() });
Solved it like this:
jQuery("#table_list_1").addRowData(id, { id: id, time: wavesurfer.getCurrentTime() });
So instead of "undefined" I just gave it "id"
This solved my select problem too.

How to set a text to Jqgrid dropdown?

I want to set a default value to jqgrid dropdown when click the add new button. My Jqgrid code is following.
jQuery("#grdDrawdownSchedule").jqGrid({
url: RootUrl + 'ECB/DDSGridData',
datatype: 'json',
mtype: 'POST',
height: 130,
colNames: ['id', 'Drawdown Date', 'Currency', 'Amount'],
colModel: [
{ name: 'id', index: 'id', width: 30, sorttype: "int", editable: false, hidden: true },
{ name: 'DdDate', index: 'DdDate', width: 130, align: 'left', editable: true,
editoptions: {
readonly: 'readonly',
size: 10, maxlengh: 10,
dataInit: function (element) {
$(element).datepicker({ dateFormat: 'dd-M-yy', changeMonth: true,
changeYear: true, constrainInput: false, showOn: 'both',
buttonImage: RootUrl + 'Content/Images/grid_Calendar.png',
buttonText: 'Show Calendar',
buttonImageOnly: true
});
}
}
},
{ name: 'CurrencyName', index: 'CurrencyName', width: 120, editable: true, edittype: "select" },
{ name: 'Amount', index: 'Amount', align: "right", width: 120, editable: true,
editoptions: { size: "20", maxlength: "16", dataInit: function (element) {
$(element).keypress(function (e) {
$('#AvgMaturityLoan').val("0");
if (e.which != 8 && e.which != 0 && e.which != 46 && (e.which < 48 || e.which > 57)) {
return false;
}
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 46 && this.value.split('.').length > 1)
return false;
});
}
}
},
//{ name: 'tadte', index: 'tdate', width: 130, "editable": true, "sorttype": "date", editrules: { "date": true }, "editoptions": { "dataInit": "initDateEdit"} },
],
loadComplete: function () {
$("#grdDrawdownSchedule").setColProp('CurrencyName', { editoptions: { value: JSON.parse(Currencies)} });
},
cellEdit: true,
rowNum: 100,
rownumbers: true,
cellsubmit: 'clientArray',
caption: "Drawdown Schedule",
multiselect: true,
shrinkToFit: false, forceFit: true,
width: 490,
postData: {
"lrnid": "0",
"data": ""
}
});
And my Add New button for the grid
$("#btnAddNewDrawdownSche").click(function () {
if (ValidateRow($("#grdDrawdownSchedule"))) {
var idAddRow = $("#grdDrawdownSchedule").getGridParam("reccount")
emptyItem = [{ id: idAddRow + 1, DrawdownDate: "", Currency: "", amount: ""}];
jQuery("#grdDrawdownSchedule").jqGrid('addRowData', 0, emptyItem);
$("#grdDrawdownSchedule").jqGrid('setCell', rowId, 'CurrencyName', selectedLoanCurrencyValue);
}
});
When I click the Add New button, Then initially I want to set the 'INR' value to the CurrencyName dropdown column. So how to set the default value to the Jqgrid's column.

JQGrid date sorting and search

I am currently displaying a particular set of data in jqgrid. I want to sort and search the column Job Date, but it does not work.
The date is being displayed as 2015-08-26 but neither sorting nor search works.
Am I missing something.
var gridSelector = "#tblist";
var emptyMsgDiv = $("<div style=\"text-align:center\"><span style='color:red;font-size:24px'>No records found</span></div>");
jQuery(gridSelector).jqGrid({
url: '#Url.Action("ListActivities", "DailyActivity")',
loadonce: true,
datatype: 'json',
shrinkToFit: true,
autowidth: true,
mtype: 'GET',
ignoreCase: true,
colNames: ['Edit', 'ActivityID', 'Job No', 'Job Date',...],
colModel: [
{ name: 'Edit', index: 'Edit', formatter: EditBind, width: '50px', search: false, sortable: false },
{ name: 'ActivityID', index: 'ActivityID', hidden: true },
{ name: 'DOWJobNumber', index: 'DOWJobNumber', align: 'left', width: '100px' },
{
name: 'DOWJobDate', index: 'DOWJobDate', width: '70px',
formatter: 'date',
sorttype: 'date',
formatoptions: {srcformat:'ISO8601Long', newformat: 'ISO8601Short' },
datefmt: 'ISO8601Short',
searchoptions: {
sopt: ['eq', 'gt', 'ge'],
dataInit: function (el) {
$(el)
.datepicker({ dateFormat: "yy-mm-dd" })
.change(function () {
$(gridSelector)[0].triggerToolbar();
});
}
}
},
{ ... },...
],
height: 'auto',
pager: '#gridpager',
rowNum: 20,
rowList: [5, 10, 20, 50, 100],
sortname: 'ActivityID',
sortorder: 'desc',
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
loadError: function (xhr, st, err) {
bootbox.alert("Error retrieving data!");
},
emptyrecords: 'No Records found',
loadComplete: function () {
emptyMsgDiv.insertAfter($('#tblist').parent());
var ts = this;
if (ts.p.reccount === 0) {
$(this).hide();
emptyMsgDiv.show();
} else {
$(this).show();
emptyMsgDiv.hide();
}
}
})
.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
Edit: It looks like the search is being made on the JSON format(/Date(1430937000000)/). How can this be changed to search and sort using the specified date format
I had to format the date time as text in the controller and processed it in the JQGrid as below
{
name: 'DOWJobDateText', index: 'DOWJobDateText', width: '80px',
formatter: 'date',
sorttype: 'date',
formatoptions: { srcformat: 'd/m/Y', newformat: 'd/m/Y' },
datefmt: 'd/m/Y',
searchoptions: {
dataInit: function (el) {
$(el)
.datepicker({ dateFormat: "dd/mm/yy" })
.change(function () {
$(gridSelector)[0].triggerToolbar();
});
}
}
}

Unable to set date format & dropdown text in jqGrid

I am using jqGrid to display data. Data is in xml format.
I am unable to format date column (source format : yyyyMMdd, target format : dd-mm-yyy).
My Grid is unable to display text value from select, It shows values instead of text.
Strange thing is it is working in some other screen.
<SalesOpportunitiesLines>
<row>
<LineNum>0</LineNum>
<SalesPerson>1</SalesPerson>
<StartDate>20131126</StartDate>
<ClosingDate>20131126</ClosingDate>
<StageKey>1</StageKey>
<PercentageRate>0.000000</PercentageRate>
<MaxLocalTotal>1000000.000000</MaxLocalTotal>
<DocumentType>bodt_MinusOne</DocumentType>
<BPChanelName>ACCM Services</BPChanelName>
<BPChanelCode>CLINAC0709</BPChanelCode>
<SequenceNo>366</SequenceNo>
<DataOwnershipfield>1</DataOwnershipfield>
<BPChannelContact>1212</BPChannelContact>
</row>
</SalesOpportunities>
$("#uxStages").jqGrid({
datatype: 'xmlstring',
datastr: xmlstring,
mtype: 'GET',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
xmlReader: { repeatitems: false, root: "BO>SalesOpportunitiesLines", row: 'row' },
colNames: ['LineNum', 'Star tDate', 'Clos Date', 'Sales Employee', 'Stage', 'Percentage', 'Potential Amount', 'Document Type', 'Doc. No.', 'Owner'],
colModel: [
{ name: 'LineNum', key: true, index: 'LineNum', hidden: true, sortable: false, width: 60 },
{ name: 'StartDate', key: false, index: 'StartDate', sortable: false, align: "left", width: 90,
editable: true,
formatter: 'date',
formatoptions: { srcformat: 'yyyyMMdd', newformat: 'd-M-y' },
editoptions: {
dataInit: function (elem) {
$(elem).datepicker({ dateFormat: 'dd-M-yy' });
}
}
},
{ name: 'ClosingDate', key: false, index: 'ClosingDate', sortable: false, align: "left", width: 90,
editable: true,
formatter: 'date',
formatoptions: { srcformat: 'yyyyMMdd', newformat: 'd-M-y' },
editoptions: {
dataInit: function (elem) {
$(elem).datepicker({ dateFormat: 'dd-M-yy' });
}
}
},
{ name: 'SalesPerson', key: false, index: 'SalesPerson', sortable: false, width: 80,
editable: true,
edittype: "select"
},
{ name: 'StageKey', key: false, index: 'StageKey', hidden: false, sortable: false, width:80,
editable: true,
edittype: "select"
},
{ name: 'PercentageRate', key: false, index: 'PercentageRate', sortable: false, width: 60 },
{ name: 'MaxLocalTotal', key: false, index: 'MaxLocalTotal', sortable: false, width: 100,
editable: true,
edittype: "text",
formatter: 'currency',
formatoptions: { thousandsSeparator: ',' }
},
{ name: 'DocumentType', key: false, index: 'DocumentType', sortable: false, width: 90,
editable: true,
edittype: 'select',
formatter: 'select',
editoptions: { value: "bodt_MinusOne:;bodt_Quotation:Sales Quotations;bodt_Order:Sales Orders;bodt_DeliveryNote:Deliveries;bodt_Invoice:A/R Invoice" }
},
{ name: 'DocumentNumber', key: false, index: 'DocumentNumber', sortable: false, width: 40 },
{ name: 'DataOwnershipfield', key: false, index: 'DataOwnershipfield', hidden: false, sortable: false, width: 60,
editable: true,
edittype: "select"
}
],
rowNum: 100,
viewrecords: true,
gridview: true,
rownumbers: true,
height: 150,
loadonce: true,
width: 1120,
scrollOffset: 0,
ondblClickRow: function (rowid) {
var grid = $("#uxStages");
var selectedRowId = grid.jqGrid('getGridParam', 'selrow');
lastSelection = selectedRowId;
grid.jqGrid('editRow', selectedRowId, true, null, null, null, null, OnSuccessEdit_Stages);
$('#' + selectedRowId + "_StageKey").css('width', '100%');
$('#' + selectedRowId + "_SalesPerson").css('width', '100%');
$('#' + selectedRowId + "_DataOwnershipfield").css('width', '100%');
},
loadComplete: function () {
var ids = $("#uxStages").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
if (i < ids.length - 1) {
$('#' + $.jgrid.jqID(id)).addClass('not-editable-row');
$('#' + $.jgrid.jqID(id)).addClass('ui-state-error');
}
}
},
onSelectRow: function (id) {
if (id && id !== lastSelection) {
var grid = $("#uxStages");
$('#uxStages').saveRow(lastSelection);
}
}
}).jqGrid('navGrid', { edit: true, edit: true, add: true, del: true, searchOnEnter: false, search: false }, {}, {}, {}, { multipleSearch: false }).trigger('reloadGrid');
$("#uxStages").setColProp('SalesPerson', { edittype: "select", editoptions: { value: GetSalesValues()} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").setColProp('StageKey', { edittype: "select", editoptions: { value: GetStagesValues()} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").setColProp('DataOwnershipfield', { edittype: "select", editoptions: { value: GetDataOwnershipValues()} }); //Here i m fetching values in namedvalue pairs
Can anybody help me out?
The predefined formatter: "date" of jqGrid don't support input fields without separators. So you have to use custom formatter. The implementation could be something like the following
formatter: function (cellValue, opts, rawdata, action) {
if (action === "edit") {
// input data have format "dd-mm-yy" format - "20-03-2015"
var input = cellValue.split("-");
if (input.length === 3) {
return input[0] + "-" + input[1] + "-" + input[2];
}
} else if (cellValue.length === 8) {
// input data have format "yymmdd" format - "20150320"
var year = cellValue.substr(0,4), month = cellValue.substr(4,2),
day = cellValue.substr(6,2);
return day + "-" + month + "-" + year;
}
return cellValue; // for empty input for example
}
Depend on other options (like the usage of loadonce: true) and depend on exact version of jqGrid which you use, you could need to implement additional callbacks in the column. For example if you use loadonce: true then the editing data will be saved locally. To hold the data in the same format as input data one can use saveLocally callback of free jqGrid (see here). In the case you can implement saveLocally callback in the column as the following
saveLocally: function (options) {
var input = String(options.newValue).split("-");
options.newItem[options.cmName] = input.length === 3 ?
input[2] + input[1] + input[0] :
options.newValue;
}
See the corresponding demo uses the above code. It uses local input data in the same format. The date will be displayed in the desired format, but the edited data will be saved locally in the same format like original date.

Categories

Resources