Change JQGrid Cell value on Button Click - javascript

I am using jqgrid in asp.net webforms. I have a column which name is Actions, in which I have button Add I want that when I click on add button, then cell value should be changed. Like I have button in this cell, when I click on add button, then it should change with text. Please, guide me. Code is given below which i am using.
<table id="jQGridDemo">
</table>
<div id="jQGridDemoPager">
</div>
 
jQuery("#jQGridDemo").jqGrid({
url: 'HttpHandlers/CustomersList.ashx',
datatype: "json",
colNames: ['Opted-In', 'Name', 'Email', 'Filter Matches', 'Customer Id','Actions'],
colModel: [
{ name: 'OptedIn', index: 'OptedIn', width: 40,align:'center', stype: 'text', formatter: OptedInValue },
{ name: 'CustomerName', index: 'CustomerName', width: 90, stype: 'text', sortable: true },
{ name: 'CustomerEmail', index: 'CustomerEmail', width: 110, stype: 'text', sortable: true },
{ name: 'FilterLetter', index: 'FilterLetter', width: 60 },
{ name: 'CustomerId', index: 'CustomerId', width: 60, hidden: true },
{ name: 'Actions', index: 'Actions',editable:true, width: 60,align:'center',formatter: ButtonValue }
],
width: 600,
height:300,
rowNum: 30,
mtype: 'GET',
loadonce: true,
rowList: [30, 60, 90],
pager: '#jQGridDemoPager',
sortname: 'OptedIn',
viewrecords: true,
sortorder: 'asc',
caption: "Customer List"
});
function ButtonValue(cellvalue, options, rowObject) {
var filterLetter = rowObject.FilterLetter;
var link = '';
if (filterLetter == " A") {
link = '<button type="button" onclick=addGridCustomer(' + rowObject.CustomerId +')>Add</button>';
} else {
link = '<div id="rowelder"><button type="button" onclick=removeGridCustomer(' + rowObject.CustomerId + ',' + options.rowId +')>Remove</button></div>';
}
return link;
}
function OptedInValue(cellvalue, options, rowObject) {
var optedIn = rowObject.OptedIn;
var link = '';
if (optedIn == true) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_success.png" />';
}
else if (optedIn == false) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_error.png" />';
}
return link;
};
function removeGridCustomer(id,rowId) {
debugger
var rowData = $('#jQGridDemo').jqGrid('getRowData', rowId);
rowData.Actions = '12321';
$('#jQGridDemo').jqGrid('setRowData', rowId, rowData);
$('#<% = hdCustomer.ClientID %>').val($('#<% = hdCustomer.ClientID %>').val() + id + ',');
UpdateFiltersForCusRemove(id);
}

i work on this problem and found the solution here below is the problem of my solution.
function ButtonValue(cellvalue, options, rowObject) {
var filterLetter = rowObject.FilterLetter;
var Id = qs("id");
var link = '';
if (Id != 0) {
link = '<div id="addbutton"><button type="button" onclick=addGridCustomer(' + rowObject.CustomerId + ',' + options.rowId + ')>Add</button></div>';
}
else {
link = '<div id="removecustomer"><button type="button" onclick=removeGridCustomer(' + rowObject.CustomerId + ',' + options.rowId + ')>Remove</button></div>';
}
return link;
}
function OptedInValue(cellvalue, options, rowObject) {
var optedIn = rowObject.OptedIn;
var link = '';
if (optedIn == true) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_success.png" />';
}
else if (optedIn == false) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_error.png" />';
}
return link;
};
function removeGridCustomer(id, rowId) {
debugger
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div button').hide();
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div').append('to be removed ..');
$('#<% = hdCustomer.ClientID %>').val($('#<% = hdCustomer.ClientID %>').val() + id + ',');
//Update Filters in case of removal
UpdateFiltersForCusRemove(id);
}
function addGridCustomer(id, rowId) {
$('#<% = hdCustomer.ClientID %>').val($('#<% = hdCustomer.ClientID %>').val() + id + ',');
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div button').hide();
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div').append('to be added ..');
//Update Filters in case of removal
UpdateFiltersForCusAdd(id);
}
function UpdateFiltersForCusAdd(a) {
var filterLtr = $("#lblF" + a).text().trim();
var count = 0;
count = parseInt($("#filterL" + filterLtr).text().trim()) - 1
$("#filterL" + filterLtr).text(count);
TotalCustomers(+1);
}

Related

How to make a column value copyable and not editable in Ag-grid - JavaScript

I have a javascript grid (ag grid)
var columnDefinitions = [
{
headerName: 'Item Number',
field: 'ItemNumber',
width: 140,
editable: editable && status !== 'Open',
cellClass: 'ag-autocomplete',
cellEditor:Grids.CellEditors.ItemEditor({
updateCallback: function (rowData, selectedItem) {
rowData.ItemId = selectedItem.Id;
rowData.Description = selectedItem.Description;
},
getInitialFilters: function () {
return [
{ Identifier: "VId", Values: [$("#Id").val()] }
];
},
searchDefinition: 'InvItems.json',
autocompleteSearchDefinition: 'InvDetail.json'
})
},
.....
{
headerName: 'Tracking Number',
field: 'TrackingNumber',
width: 120,
cellRenderer: function (params) {
if (params.data.TrackingNumber != null) {
var url;
if (params.data.Carrier == 'UPS') {
url = 'https://wwwapps.ups.com/tracking/tracking.cgi?tracknum=';
}
if (params.data.Carrier == 'USPS') {
url = 'https://tools.usps.com/go/TrackConfirmAction.action?tLabels=';
}
return "<a target='_blank' href='" + url
+ params.value
+ "'>" + params.value + "</a>";
}
else {
return '';
}
}
},
I want to make the column "TrackingNumber" copyable. I don't want to make it editable. anything I try that make it like a textbox and I can copy the value I can edit it too that I don't want that.
Add enableCellTextSelection: true to your grid options. Docs here

addrow undefined and remove button doesn't work in datatables

Yesterday i post a question ask about my addrow button.Problem solved.
It run smoothly,but I have new problems.
Firstly, my delete button which I was used the remove()API is not working.
Secondly, everytime I reload the page, in the first row col5 will have the value : undefined
Once again, I appreciate every answer to this question.
var table = null;
var arrData = [];
var arrDataPG = [];
arrData.push({
STT: 1,
id: 1,
product_type: "",
condition1: "",
rebate: 0.0,
});
$(document).ready(function () {
InitTable();
});
function InitTable() {
if (table !== null && table !== undefined) {
table.destroy();
}
table = $('#tableh').DataTable({
data: arrData,
"columns": [
{ "width": "25px" },
{ "width": "300px" },
{ "width": "300px" },
{ "width": "120px" },
{ "width": "200px" },
{ "width": "25px" },
],
columnDefs: [
{
title: "STT",
targets: 0,
data: null,
render: function (data, type, row, meta) {
return (meta.row + meta.settings._iDisplayStart + 1);
},
},
{
title: "Loại sản phẩm*",
targets: 1,
data: null,
render: function (data, type, row, meta) {
return '<textarea style="width: 300px;" id="product_type' + data.id + '" type="text" onchange="ChangeProductType(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.product_type + '">' + data.product_type + '</textarea>';
}
},
{
title: "Điều kiện*",
targets: 2,
data: null,
render: function (data, type, row, meta) {
return '<textarea style="width: 300px;" id="condition1' + data.id + '" type="text" onchange="ChangeCondition1(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.condition1 + '">' + data.condition1 + '</textarea>';
}
},
{
title: "Rebate(%)*",
targets: 3,
data: null,
width: "70",
render: function (data, type, row, meta) {
return '<div><input id="rebate' + data.id + '" type="number" style="width: 70px;" onchange="ChangeRebate(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.rebate + '"></div>';
}
},
{
title: "Ghi chú",
targets: 4,
data: null,
width: "250",
render: function (data, type, row, meta) {
return '<textarea style="width:200px;" id="note' + data.id + '" type="text" onchange="ChangeNote(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.note + '">' + data.note + '</textarea>';
}
},
{
title: "",
targets: 5,
data: null,
className: "dt-center",
width: "70",
render: function (data, type, row, meta) {
return '<div class="btn btn-danger removePG" style="cursor: pointer;font-size:25px;" onclick=removePG(\'' + data.id + '\')><i class="fa-solid fa-trash"></i></div>'
}
},
],
});
table.columns.adjust().draw();
}
$('#addRow').on('click', function () {
console.log(arrData.length);
if (arrData != '') {
var ida = arrData[0].id;
} else {
var ida = 1;
}
for (var i = 0; i < arrData.length; i++) {
if (arrData[i].id > ida) {
ida = arrData[i].id;
}
};
arrData.push({
STT: ida + 1,
id: ida + 1,
product_type: "",
condition1: "",
rebate: 0.0,
note: ""
});
if (table != null) {
table.clear();
table.rows.add(arrData).draw();
}
});
$('#tableh').on('click','.removePG', function () {
var tableq = $('#table_h').DataTable();
tableq
.row($(this).parents('tr'))
.remove()
.draw();
});
function removePG(idc) {
let id = parseInt(idc);
if (arrData !== undefined) {
var find = arrData.find(function (item) {
return item.id === id;
});
if (find !== undefined) {
arrData = arrData.filter(function (item, index) {
return item.id !== id;
});
};
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet"type="text/css"href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<table id="tableh" class="cell-border hover" style="width:100%"></table>
<button style="width: 86px;" id="addRow" class="btn btn-success add">Addrow<i class="fa fa-plus" aria-hidden="true"></i></button>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
<script src="https://kit.fontawesome.com/60bf89e922.js" crossorigin="anonymous"></script>

Get expand and checkbox with multiple column in ng-grid

I want to create a grid which shows expand/collapse and checkbox with multiple column.
For this I create a sample which expand at first level and show check box with next level.
My sample is - plunker
$scope.customExpand = function (row, gridId) {
// find which grid (in case more than one on page)
var selectedGrid;
if (gridId === $scope.gridOptions.gridId) {
selectedGrid = $scope.gridOptions.ngGrid;
}
// first collapse all others
/* angular.forEach(selectedGrid.rowFactory.aggCache, function (aggRow, key) {
if (aggRow.isAggRow && aggRow.collapsed === false) {
aggRow.toggleExpand();
}
});*/
// then scroll to row for this group
var rowNum = 0;
angular.forEach(selectedGrid.rowFactory.aggCache, function (aggRow, key) {
if (aggRow.label == row.label) {
rowNum = key;
}
});
selectedGrid.$viewport.scrollTop(rowNum * selectedGrid.config.rowHeight);
// then expand the row
row.toggleExpand();
}
$scope.gridData = [];
$scope.aggregateLots = function(row) {
var lots = 0;
angular.forEach(row.children, function(subrow) {
lots += subrow.entity.lots;
});
return lots;
}
$scope.gridOptions = {
aggregateTemplate: "<div ng-click=\"debugger;customExpand(row,gridId)\" ng-style=\"rowStyle(row)\" class=\"ngAggregate\">\r" +
"\n" +
"<div class='ngCell col3 col3t'><div class='ngCellText col3 col3t'>{{row.children[0].entity.cname}}</div></div>\r\n" +
"<div class='ngCell col4 col4t'><div class='ngCellText col4 col4t'>{{row.children[0].entity.maturity | date:\'dd-MMM-yy\' }}</div></div>\r\n" +
"<div class='ngCell col5 col5t'><div class='ngCellText col5 col5t'>{{row.children[0].entity.bs}}</div></div>\r\n" +
"<div class='ngCell col6 col6t'><div class='ngCellText col6 col6t'>{{row.children[0].entity.price}}</div></div>\r\n" +
"<div class='ngCell col7 col7t'><div class='ngCellText col7 col7t'>{{row.totalChildren()}}</div></div>\r\n" +
"<div class='ngCell col8 col8t'><div class='ngCellText col8 col8t'>{{aggregateLots(row)}}</div></div>\r\n" +
"\n" +
" <div class=\"{{row.aggClass()}}\"></div>\r" +
"\n" +
"</div>\r" +
"\n",
data: 'griddata',
showFilter: false,
width: '572px',
showGroupPanel: false,
groups: ['groupCol'],
enableRowSelection: false,
multiSelect: true,
selectWithCheckboxOnly: true,
showSelectionCheckbox: true,
checkboxCellTemplate: '<div class="ngSelectionCell" ng-class="Header"><input tabindex="-1" class="ngSelectionCheckbox" class="Header" type="checkbox" ng-checked="row.selected" /></div>',
columnDefs: [{
field: 'groupCol',
visible: false
}, {
field: 'cname',
displayName: 'Contract',
width: '150px'
}, {
field: 'maturity',
displayName: 'Maturity',
width: '112px',
cellFilter: 'date:\'dd-MMM-yy\''
}, {
field: 'bs',
displayName: 'B/S',
width: '50px'
}, {
field: 'price',
displayName: 'Price',
width: '100px'
}, {
field: 'identid',
displayName: 'Trades',
width: '100px'
}, {
field: 'lots',
displayName: 'Lots',
width: '60px'
}]
};
_.each(tradelist, function(trade) {
trade.groupCol = trade.cname ;
});
$scope.griddata = _.sortBy(tradelist, function(row) {
return row.groupCol;
});
Now my requirement is
Show checkbow with First level
On second level expand also show with it to expand at third level.
show checkbox with third level.
For example -
And all this I want to create only with ng-grid, not with ui-grid or any other.

How to use "formatter" dynamically in jqGrid.Is it possible?

Is there a way to dynamically use the "formatter" in jqGrid?I want to make use of formatTitle function from the code dynamically, Here is my code:
HTML
<table id="list47"><tr><td></td></tr></table>
<div id="plist47"></div>
Javascript:
var md=[{ "id": "83123a", Name: "Name 1", "PackageCode": "83123a" },
{ "id": "83432a", Name: "Name 3", "PackageCode": "83432a" },
{ "id": "83566a", Name: "Name 2", "PackageCode": "83566a" }]
var he=["id","Name","PackageCode"];
var c=[];
for(var i=0;i<he.length;i++){
c.push('{"name":"'+he[i]+'","index":"'+he[i]+'"}');
}
var colmodel="["+c+"]"
//var colmodel= [{name:'id', index:'id', width:55},
// {name:'Name', index:'Name' },
// {name:'PackageCode', index:'PackageCode'}]
// c.push('{"name":"'+he[i]+'","index":"'+he[i]+'"'+'"formatter":'+formatTitle+'}');
jQuery("#list47").jqGrid({
//data: md,
datatype: "local",
height: 150,
rowNum: 10,
colNames: he,
colModel: jQuery.parseJSON(colmodel),
rowList: [10,20,30],
pager: "#plist47",
viewrecords: true,
caption: "json data grid"
});
for(var i=0;i<md.length;i++){
jQuery("#list47").addRowData(i+1,md[i]);
}
function formatTitle(cellValue, options, rowObject) {
return "<a href='" + rowObject.Link + "'>" + cellValue.substring(0, 45) + "..." + "</a>";
//return cellValue.substring(0, 50) + "...";
};
You have to put the formatter in a string as follows
for(var i=0;i<he.length;i++){
c.push('{"name":"'+he[i]+'","index":"'+he[i]+'"'+',"formatter":"formatTitle"'+'}');
}
Then you defind the formatter before the jqGrid code as follows
$.fn.fmatter.formatTitle = function (cellValue, options, rowObject) {
return "<a href='" + rowObject.Link + "'>" + cellValue.substring(0, 45) + "..." + "</a>";
};
Because it is wrapped in a string(formatter: "formatTitle") you cant use your former signature for the formatter which was
function formatTitle(cellValue, options, rowObject) This can be used if formatter: formatTitle which is not possible to construct dynamically
Here is a jsfiddle solution to your problem

Hide column in jQuery MultiColumn Autocomplete

I have a fine working jquery multicolumn autocomplete. Now i have to add a column which should be hidden. Basically its a ID of the values. So when the user selects the value i could able to get the ID of the selected row.
//Code:
<script type="text/javascript">
var autocompleteSource;
var colValues = [];
var columns = [{ name: 'Workflow Name', width: '200px' }, { name: 'Workflow Category', width: '150px' }, { name: 'Status', width: '100px' }, { name: 'Workflow Owner', width: '150px' }];
$.ajax({
url: "/Home/LoadWorkflowDropdown",
datatype: 'json',
mtype: 'GET',
success: OnComplete,
error: OnFail
});
function OnComplete(result) {
autocompleteSource = $.parseJSON(result)
$.each(autocompleteSource, function () {
colValues.push([this.WorkflowName, this.WorkflowCategory, this.StatusName, this.UserName]);
});
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function (index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function (index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function (ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function (index, column) {
t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>').data('item.autocomplete', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
return result;
}
});
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colValues,
select: function (event, ui) {
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});
}
</script>
Working Fiddle here
Here i have modified js code to add unique id to each record and to get that value when user selects a particular option from the auto-suggest list. Fiddle
HTML: Create a hidden field to store the id of selected option
<input type="hidden" name="selectedId" id="selectedId" />
JS: Added ids in the array and retrieved those ids in select function by index value.
var columns = [{
name: 'Color',
width: '100px'},
{
name: 'Hex',
width: '70px'}],
colors = [['Red', '#f00', '1'], ['Green', '#0f0', '2'], ['Blue', '#00f', '3']];
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colors,
select: function(event, ui) {
$('#selectedId').val(ui.item[2]);
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});

Categories