hyperlink / button with custom function call in jqgrid - javascript

I want to add a hyperlink / button in each row of jqgrid, that fires a custom javascript function. Tired of various trials.
jQuery('#ProductListGrid').jqGrid({
url: '/Product/ProductListGrid',
datatype: 'json',
multiselect: true,
height: 250,
autowidth: true,
mtype: 'GET',
loadComplete: addlinks,
colNames: ['ProductId', 'ProductName', 'edit'],
colModel: [
{ name: 'ProductId', index: 'ProductId',key:true, width: 70, hidden: true, editable: true, size: 5 },
{ name: 'ProductName', index: 'ProductName', width: 70, editable: true },
{ name: 'edit', index: 'edit', width: 70},
],
pager: jQuery('#ProductListGrid_pager'),
});
function addlinks() {
var ids = jQuery("#ProductListGrid").getDataIDs();
alert(ids);
for (var i = 0; i < ids.length; i++) {
be = "<a href='#' style='height:25px;width:120px;' type='button' title='Slet' onclick=\"ff()\" >Slet</>";
jQuery("#ProductListGrid").jqGrid('setCell', ids[i],'edit','', { act: be });
}
//for (var i = 0; i < ids.length; i++) {
// jQuery("#ProductListGrid").setCell(i, 'edit', '<a href="#">edit</edit>');
//}
}
function ff()
{
alert("hi");
}
The code in addlinks in is getting executed but there nothing appears in the column. I tried using custom formatting also but I couldnot show custom text "Edit" and link click doesnot fire the js method.

You need to call a formatter for edit column like below :
Add formatter: addLink to the last column :
colModel: [
{ name: 'ProductId', index: 'ProductId',key:true, width: 70, hidden: true, editable: true, size: 5 },
{ name: 'ProductName', index: 'ProductName', width: 70, editable: true },
{ name: 'edit', index: 'edit', width: 70,formatter: addLink},
]
add javascript function :
function addLink(cellvalue, options, rowObject)
{
//to get row Id
alert(options.rowId);
// to get product Id
alert(rowObject.ProductId);
return "<a href='#' style='height:25px;width:120px;' type='button' title='Slet' onclick=\"ff()\" >Slet</a>";
}
More Information on formatter here.

Related

Check Uncheck , check boxes inside a jqgrid or toggle

I have this code below for my jq Grid
function LeaveHalfDay() {
var url1 = URL
$("#LeaveHalfDayDataEntryList").jqGrid({
url: url1,
datatype: 'json',
mtype: 'POST',
colNames: ['RowId', 'With Halfday <br /> Morning', 'With Halfday <br /> Afternoon', 'Date', 'Day'],
colModel: [
{ name: 'rowId', index: 'rowId', hidden: true, editable: true, sortable: false, width: 80, align: 'left' },
{name: 'cbox_leave_half', index: 'cbox_leave_half', editable: true, formatter: cboxFormatterLeaveHalfDay, formatoptions: { disabled: false }, edittype: 'checkbox', editoptions: { value: "True:False" }, sortable: false, width: 70, align: 'center' },
{ name: 'cbox_leave_halfPM', index: 'cbox_leave_halfPM', editable: true, formatter: cboxFormatterLeaveHalfDayPM, formatoptions: { disabled: false }, edittype: 'checkbox', editoptions: { value: "True:False" }, sortable: false, width: 70, align: 'center' },
{ name: 'LStartDate', index: 'LStartDate', editable: false, sortable: false, width: 70, align: 'left' },
{ name: 'LDate', index: 'LDate', editable: false, sortable: false, width: 70, align: 'left' }
],
pager: $('#LeaveHalfDayDataEntryPager'),
rowNum: 5,
rowList: [5, 10, 20],
sortname: '',
sortorder: '',
viewrecords: true,
imgpath: '/Content/themes/redmond/images/',
height: '100%',
loadComplete: function (result, rowid) {
var ids = jQuery("#LeaveHalfDayDataEntryList").getDataIDs();
var len = ids.length, newLine;
if (len < 5) {
AddNewRowToGrid(len, "#LeaveHalfDayDataEntryList");
}
$("#LeaveHalfDayDataEntryPager").css("width", "auto");
$("#LeaveHalfDayDataEntryPager .ui-paging-info").css("display", "none");
}
});
return false;
}
And this one is to click the check box name (cbox_leave_half)
$('.cbox_leave_half').live('click', function (e) {
var tr = $(e.target).closest('tr');
var target = $(e.target).is(':checked');
HalfDayrowsObj[tr[0].id].HalfDay = $(e.target).is(':checked');
_hashalfday = _hashalfday + 1;
var EmployeeId = $("#hidEmployeeId").val();
var StartDate = $("#LSDate").val();
var EndDate = $("#LEDate").val();
var noofdays = $("#txtNoDays").val();
if (StartDate != "" && EndDate != "") {
if (HalfDayrowsObj[tr[0].id].HalfDay == true) {
NoOfHalfDay = NoOfHalfDay + 4;
ComputeTotalDayHourLeave(EmployeeId, StartDate, EndDate, NoOfHalfDay);
noofdays = parseFloat(noofdays) - parseFloat('.5');
$("#txtNoDays").val(noofdays);
$("#hidNoofDays").val(noofdays);
$("#txtNoHrs").val(noofdays * 8);
}
else {
NoOfHalfDay = NoOfHalfDay - 4;
ComputeTotalDayHourLeave(EmployeeId, StartDate, EndDate, NoOfHalfDay);
}
}
});
For example I have 3 data which means I got 6 check boxes inside my JQgrid 3 for AM and 3 for PM. What i want to achieve is if i check the row 0(First row) AM check box it will check, then If i check the PM check box with the same row the PM checkbox must be uncheck. I try to use this code
if ($('.cbox_leave_half').is(':checked))
{ $('.cbox_leave_halfPM').attr("checked",false); }
But this code return all the PM check box will uncheck. What I want is to uncheck the AM/PM with the same row.
I'm using jquery <= 1.8.2 version. I know this is so old but I don't know if I switch to higher version of jquery what will happen to my project.
Could you please try with below code:
Its part of your above code
$('.cbox_leave_half').live('click', function (e) {
var tr = $(e.target).closest('tr');
var target = $(e.target).is(':checked');
if ($(this).is(':checked))
{
$(tr).find('.cbox_leave_halfPM').attr("checked",false);
}
...
...
Here on click of .cbox_leave_half we are searching for associated .cbox_leave_halfPM present in same row i.e. tr element. I hope this will hep you a bit.

get id of the row on click

guys i am using jqgrid ... i want to get id of the row upon clicking on the image only without selecting the whole row first .. here is my code
<script type="text/javascript">
$(document).ready(function() {
$("#jqGrid").jqGrid({
url: 'data.json',
datatype: "json",
styleUI: "Bootstrap",
colModel: [{
label: 'Order ID',
name: 'OrderID',
key: true,
width: 75,
hidden: true
}, {
label: 'From Date',
name: 'FromDate',
width: 150,
editable: true,
edittype: "text",
id: "ui-datepicker-div",
editoptions: {
dataInit: function(element) {
$(element).datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
orientation: 'auto bottom'
});
},
},
}, {
label: 'To Date',
name: 'ToDate',
width: 150,
editable: true,
edittype: "text",
editoptions: {
dataInit: function(element) {
$(element).datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
orientation: 'auto bottom'
});
},
},
}, {
label: 'Customer ID',
name: 'CustomerID',
width: 150
}, {
label: 'Ship Name',
name: 'ShipName',
width: 200
}, {
label: 'Row Data',
name: 'RowData',
align: 'center',
formatter: function() {
return "<img src='resources/icon.jpg' onclick='OpenDialog()' alt='Data Row' />";
width = 15;
}
}, ],
loadonce: true,
......
});
});
...........
function OpenDialog() {
var result = "";
var grid = $("#jqGrid");
var rowKey = grid.getGridParam("selrow");
rowData = grid.getLocalRow(rowKey);
for (var item in rowData) {
if (item == 'RowData') {
break;
}
result += rowData[item] + ', ';
}
alert(result);
}
any help please how to get id of row upon only clicking on the image ??.. thanks a lot .. thanks in advance
use this html:
onclick='OpenDialog(this)'
and in OpenDialog use closest jquery method:
function OpenDialog(element) {
var id = $(element).closest('tr').attr('id');
...
}

export jqgrid data into excel on checkbox 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.

How to get all row ids of jqgrid by class

I want to get all row ids by use of row css class of a jqgrid in a method called in gridcomplete.But it is only returning rows of current page.
I want to get all row ids present in the jqgrid.
Below is my code.
function GetAllCompanyProducts(productData) {
/// <summary>method to load the Proposal grid</summary>
//Load the grid
var tabelWidth = $("#tblCompanyProducts").width();
jQuery("#tblCompanyProducts").jqGrid({
datatype: 'local',
data: productData,
jsonReader: { repeatitems: false },
loadui: "block",
autowidth: true,
mtype: 'get',
rowNum: 30,
rowList: [30, 100, 200],
viewrecords: true,
colNames: ['ProductId', 'ProductName', 'Price'],
colModel: [
{ name: 'ProductId', index: 'ProductId', width: '30%' },
{ name: 'ProductName', index: 'ProductName', width: '30%' },
{ name: 'Price', index: 'Price', width: '30%' }
],
sortname: 'ProductId',
sortorder: 'asc',
caption: "Product List",
width: tabelWidth - 10,
pager: '#divPager',
height: "100%",
hoverrows: true,
onPaging: function () {
$("#tblCompanyProducts").trigger('reloadGrid');
},
});
$("#tblCompanyProducts").jqGrid('setGridParam', { gridComplete: MakeGridRowsDraggable($("#" + this.id)) });
}
function MakeGridRowsDraggable(grid) {
/// <summary></summary>
/// <param name="grid" type=""></param>
//$("#tblCompanyProducts").val(new Date().getTime());
var searchResultsRows = $("#tblCompanyProducts .ui-row-ltr");
}
The above code returning only the rows set in the first page.
Can anybody help me on this..

jqGrid shows + sign even after subgrid has no data using xml

I am using jqGrid to show data with subgrid.
Data is in xml format.
$("#UDFs").jqGrid({
ajaxGridOptions: { contentType: 'application/xml; charset=utf-8' },
datatype: 'xmlstring',
datastr: data,
xmlReader: { root: "Response", row: "Data>UDFS>row", repeatitems: false, id: "FieldID" },
subGrid: true,
subgridtype: 'xml',
subGridOptions: { "plusicon": "ui-icon-triangle-1-e", "minusicon": "ui-icon-triangle-1-s", "openicon": "ui-icon-arrowreturn-1-e" },
subGridRowExpanded: function (subgrid_id, row_id) {
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id + "_t";
pager_id = "p_" + subgrid_table_id; $("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + pager_id + "' class='scroll'></div>");
jQuery("#" + subgrid_table_id).jqGrid(
{
datastr: $($.parseXML(data)).find('Response>Data>UDFS>row:has(FieldID:contains('+ row_id+'))').XmlToString(),
datatype: "xmlstring",
colNames: [ 'Code', 'Name'],
colModel: [
{ name: "Code", index: "Code", width: 130 },
{ name: "Name", index: "Name", width: 70 }
],
xmlReader: { root: "row", row: "ValidValues>row", repeatitems: false, id: "FieldID" },
rowNum: 20,
pager: pager_id,
height: '100%'
});
jQuery("#" + subgrid_table_id).jqGrid('navGrid', "#" + pager_id, { edit: false, add: false, del: false })
},
colNames: ['#', 'TableID', 'SAPType', 'SAPSubType', 'SAPValidation', 'FieldID', 'AliasID', 'Descr', 'TypeID', 'SizeID', 'EditSize', 'Dflt', 'NotNull', 'RTable', 'RelUDO', 'ValidValues'],
colModel: [
{
index: 'Tick',
name: 'Tick',
width: 50,
resizable: false,
editable: true,
align: 'center',
edittype: 'checkbox',
formatter: "checkbox",
formatoptions: { disabled: false },
classes: 'check',
editrules: { required: false }, editoptions: { size: 39, value: "True:False" }
},
{ name: 'TableID', index: 'TableID', align: "left", width: 40, hidden: true },
{ name: 'SAPType', index: 'SAPType', align: "left", width: 80 },
{ name: 'SAPSubType', index: 'SAPSubType', align: "left", width: 80 },
{ name: 'SAPValidation', index: 'SAPValidation', align: "left", width: 80 },
{ name: 'FieldID', index: 'FieldID', align: "left", width: 40, hidden: false },
{ name: 'AliasID', index: 'AliasID', align: "left", width: 180 },
{ name: 'Descr', index: 'Descr', align: "left", width: 180 },
{ name: 'TypeID', index: 'TypeID', align: "left", width: 80 },
{ name: 'SizeID', index: 'SizeID', align: "left", width: 80 },
{ name: 'EditSize', index: 'EditSize', align: "left", width: 80 },
{ name: 'Dflt', index: 'Dflt', align: "left", width: 80 },
{ name: 'NotNull', index: 'NotNull', align: "left", width: 80 },
{ name: 'RTable', index: 'RTable', align: "left", width: 80 },
{ name: 'RelUDO', index: 'RelUDO', align: "left", width: 80, hidden: false },
{ name: 'ValidValues', index: 'ValidValues', align: "left", width: 80, formatter: formatToLink, unformat: UnformatFromLink }
],
rowNum: 15,
mtype: 'POST',
pager: "#UDFsMap",
gridview: true,
rownumbers: true,
loadonce: true,
forceFit: true,
width: 1100,
height: 250,
caption: 'Select UDF from the below list.',
multiselect: false,
loadComplete: function () {
$(this).HideBusy();
},
ondblClickRow: function (rowid, iRow, iCol, e) {
selectedRowId = $("#ObjType").jqGrid('getGridParam', 'selrow');
ObjectTypeID = $("#ObjType").jqGrid('getCell', selectedRowId, 'ObjectTypeID');
// $("#SelectCustomer").dialog('close');
// xmlDoc1 = $.parseXML(xmlString);
// $xml1 = $(xmlDoc1);
// $(this).SetValuesToControl("Landscape", $xml1);
// $("#uxTask").attr("binding", "true");
}
}).jqGrid('navGrid', '#UDFsMap', { edit: false, add: false, del: false, search: true });
When grid displays on page, it shows Plus (+) sign / arrow even if the subgrid does not have data.
Is it possible to hide / remove this Plus (+) sign / arrow when there is no data in subgrid?
UPDATED:
I tried your proposed solution and saw samples also, it works for me from 2nd page onwards. its not working for 1st page.
loadComplete: function (data) {
var grid = $("#UDFs");
var $self = $(this), rowIds = $self.jqGrid("getDataIDs"), item, i, l = rowIds.length;
for (i = 0; i < l; i++) {
item = $self.jqGrid("getLocalRow", rowIds[i]);
debugger;
if (item.ValidValues == null || item.ValidValues.length === 0) {
// subggrid is empty
$("#" + rowIds[i]).find(">.ui-sgcollapsed").unbind("click").html("");
}
}
$(this).HideBusy();
},
When the grid load, it works from 2nd page onward. Please see the screen shot. In the last column (ValidValues), if exist then show subgrid / plus sign otherwise hide.
In below screen shot it is working.
I recommend you to hide the "+" icon of rows which have no subgrids inside of loadComplete callback. The first parameter of callback loadComplete contains all parsed XML data (datastr: data) which you use to fill the grid. See the old answer which describes the main idea of the hiding of the rows. You can get the ids of the rows of the current page by usage of getDataIDs and to find the corresponding item in XML data by the id. Then you can examine the information about subgrids and to hide the icon.
The demo demonstrates the approach in case of usage JSON data. You can do the same with XML data too. You need just change the criteria for testing the input data for the existence of subgrid.
UPDATED: The code which you posed in UDPATED works only with the second part because you use datatype: 'xmlstring'. At the first loading the data in loadComplete are XML data and you should be more careful how to parse it. My demo used JSON instead of XML data. So you should use the demo which I posted as the template, but you have to modify it based on the format of the data which you use.

Categories