How to show jqgrid columns editable on page load - javascript

I am working on JQgrid in which 2 columns need to be editable, I've achieved it using below options in colModel.
{
name: 'Action',
index: 'Action',
editable: true,
edittype: "select",
formatter: 'select',
editoptions: {
value: {
1: 'Approve',
2: 'Reject'
}
},
editrules: {
required: true,
custom: true,
custom_func: actionCheck
}
},
and below two options in jqgrid
cellEdit: true,
cellsubmit: 'clientArray',
But with this, I have to click on the column to be able to edit it.
I also have a column named comments with edittype:"textarea".
What I want is, when users open the page they see dropdowns and textareas in both columns of all rows and when they click the submit button after entering the data, I grab all of it in an array, which I will then use to update my SharePoint list.
Is this possible? if so please let me know how.
here's what I currently have,

With celEdit you can't do what you want. You can use both methods editRow and saveRow. Please, check the docs for this purpose.
The idea is to call editRow after the data is loaded. This can be done with setTimeout function after the jqGrid code. Make these two fields editable and do.
...
jqGrid({
...
});
setTimeout(function() {
var grid = $("#jqGrid");
var ids = grid.jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
grid.jqGrid('editRow',ids[i]);
}
}, 800);
After that you can save the data on button click. The button should be defined somewhere in the DOM.
function saveRows() {
var grid = $("#jqGrid");
var ids = grid.jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
grid.jqGrid('saveRow', ids[i]);
}
}
Please check the similar example here

Related

How do I add a button column to Ag Grid Javascript grid

I have managed to get the community version of AgGrid (Javascript) to work
However, I cant get a button to work?
function drop( id) {
alert(id);
}
var columnDefs = [
{ headerName: "HELLO", field: "name", sortable: true, filter: true },
{ headerName: 'One', field: 'fieldName',
cellRenderer : function(params){
return '<div><button (click)="this.drop(params.id)">Click</button></div>'
}
}
];
I need the function to be called when the user clicks on the button
Nothing happens at all? No errors in the console even?
What am I doing wrong?
Is this functionality disabled for the community edition?
Please note that I need a Javascript solution not Angular or any other language/framework supported by the Ag Grid
Paul
While working with cellRenderer, you should not register the event like (click)="this.drop(params.id)".
Instead, register listener the javascript way. Have a look at below code.
colDef.cellRenderer = function(params) {
var eDiv = document.createElement('div');
eDiv.innerHTML = '<span class="my-css-class"><button class="btn-simple">Push Me</button></span>';
var eButton = eDiv.querySelectorAll('.btn-simple')[0];
eButton.addEventListener('click', function() {
console.log('button was clicked!!');
});
return eDiv;
}
Reference: ag-grid Cell Renderer

Button click in kendo grid column firing onclick of whole row

Our customer wanted a kendo grid where he can click anywhere on a row to open the corresponding detail page. I'm adding the rows like this:
const cols = [
{ field: "Date", title: "Date", template: "#=kendo.toString(kendo.parseDate(Date, 'yyyy-MM-dd), 'dd.MM.yyyy')#" },
{ field: "Title", title: "Title" },
{ field: "", command: ["destroy"], title: " " }];
let grid = $("#grid").kendoGrid({
dataSource: this.dataSource,
pageable: true,
filterable: true,
sortable: true,
columns: cols,
editable: "detail"
}).data("kendoGrid");
grid.one("dataBound", this.onDataBound.bind(this));
And in my function onDataBound():
const grid = $("#grid").data("kendoGrid");
$(grid.tbody).on("click", "tr", function (e) {
const rowData = grid.dataItem(this);
const URL = startInfo.ApplicationRoot + "SomeDetailPage?SomeId=" + rowData.get("SomeId");
window.open(URL, '_blank');
});
This works perfectly as expected. However, as you see, I have a column with a delete button. Here is the problem. Whenever I click on the delete button, I'm getting the confirmation message ("Are you sure to delete [...]?") and actually can delete the row successfully, but the detail page of the row opens as soon as I click the button.
How can I let the row know that it shouldn't open the detail page when I click the delete button?
You should use e.stopPropagation(); on delete button so it will not pass the event to the row also.
I've found a solution. I can check the tagName when binding the click function to the row:
$(grid.tbody).on("click", "tr", function (e) {
if (e.target.tagName == "TD") {
const URL = startInfo.ApplicationRoot + "SomeDetailPage?SomeId=" + rowData.get("SomeId");
window.open(URL, '_blank');
}
});
When I click the button, tagName get either "SPAN" or "A". Everything outside the button results in "TD".

MultiSelect dropdown widget not showing selected option?

So I am using the multiselect widget from here: http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/ and it is working fine in this instance. When I use strictly the same dropdown styling (to appear consistent) with a normal (only choose 1 option) dropdown my problem is that the drop down says 1 Selected. I need to change this to show the selected option, so 'Red' from Red, Yellow, Blue. The code that determines the selected option text is as follows:
$.widget("ech.multiselect", {
// default options
options: {
header: true,
height: 175,
minWidth: 225,
classes: '',
checkAllText: 'Check all',
uncheckAllText: 'Uncheck all',
noneSelectedText: 'Select options',
selectedText: '# selected',
selectedList: 0,
show: null,
hide: null,
autoOpen: false,
multiple: true,
position: {},
appendTo: "body"
}
So, I need the selectedText to show the selected option if the dropdown has the class .normal. Any ideas? Thanks in advance.
You have to change some code in the jquery.multiselect.js file.
Replace the update function with this code:
// updates the button text. call refresh() to rebuild
update: function() {
var o = this.options;
var $inputs = this.inputs;
var $checked = $inputs.filter(':checked');
var numChecked = $checked.length;
var value;
if(numChecked === 0) {
value = o.noneSelectedText;
} else if( numChecked===1){
value = $checked.val();
} else {
if($.isFunction(o.selectedText)) {
value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get());
} else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) {
value = $checked.map(function() { return $(this).next().html(); }).get().join(', ');
} else {
value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length);
}
}
this._setButtonValue(value);
return value;
},
I haven't tested this but tell if it works for you.
I have the same problem and im using javascript 1.7.2
The problem is the selectedText only taken into account for the first time loading and when i change the checkbox, slectedText of my button is not changing. Finally, i manage to fix the problem by modifying the jquery.multiselect.js like this :
In _create: function ()
Edit buttonlabel to:
buttonlabel = (this.buttonlabel = $(''))
.html(o.noneSelectedText)
.appendTo(button)
.attr("id", "buttonlabel_" + this.element.attr('id')),
In update: function ()
Change this.buttonlabel.html( value ) to $("#buttonlabel_" + this.element.attr("id")).text(value);
Hope this helps.
Cheers

Binding an event to an add dialog select input in jqgrid

I have a jqgrid with the add dialog enabled for adding new rows. The way I would like it to work is that the user will select from a list of drop down items and the item chosen will cause a second drop-down to be populated with data based on the first item.
For example, if my grid had two columns, one for country and one for state, when the user clicked the add button, the country input would be a drop-down, dynamically populated with countries by an ajax call. Then, when the user selects a country, the state drop-down is populated based on the country selected.
Currently I am doing something like the following:
beforeProcessing: function () {
var allcountries = ajaxcall();
$('#clientReportsGrid').setColProp('Countries', { editoptions: { value: allcountries, class: 'edit-select' }, editrules: { required: true, edithidden: true} });
},
loadComplete: function () {
$('#Countries').change(function () {
// States will be populated here
alert("changed");
});
}
The first part in beforeProcessing works fine and the countries drop-down is populated as expected. However, the event in loadComplete does not get attached to the select input with id the 'Countries' and the alert never occurs. It seems that the select object has not yet been created with loadComplete fires, but if that is the case I'm not sure where to place the logic where the states will be populated.
Any ideas?
jqGrid has no direct support of depended selects, but in the answer you will find the implementation of the scenario. The most problem is that the code is not small, but it's quickly to analyse a working code as to write your own one.
I ended up doing something like the following, its a bit redundant but it works and isn't too code heavy:
First, in the beforeProcessing callback, I populate both the countries and states drop-downs with their initial values:
beforeProcessing: function () {
var allcountries = ajaxCallToFetchCounties();
$('#clientReportsGrid').setColProp('Countries', { editoptions: { value: allcountries, class: 'edit-select' }, editrules: { required: true, edithidden: true} });
var states = ajaxCallToFetchStates();
$('#clientReportsGrid').setColProp('States', { editoptions: { value: states , class: 'edit-select' }, editrules: { required: true, edithidden: true} });
}
Then in the pager's add option, I used the beforeShowForm callback to attach a method to the change event of the countries select input, and within that method I fetch the states based on the current country and repopulate the select control:
beforeShowForm: function (form) {
$("#Countries").unbind("change").bind("change", function () {
var states = ajaxCallToFetchStates();
//Manually clear and re-populate the states select box here with the new list of states.
});
$('#tr_AccountCode', form).show();
}

jqGrid with an editable checkbox column

When using jqGrid how do you force a cell to load in its editable view on page load as well as when it is clicked?
If you set up 'cell editing' like below, the check box only appears when you click on the cell.
{ name: 'MyCol', index: 'MyCol', editable:true, edittype:'checkbox', editoptions: { value:"True:False" },
cellEdit:true,
Also on clicking checkbox, is there a way of sending a AJAX post to server instantly rather than having to rely on the user pressing enter?
To allow the checkboxes to always be click-able, use the checkbox formatter's disabled property:
{ name: 'MyCol', index: 'MyCol',
editable:true, edittype:'checkbox', editoptions: { value:"True:False"},
formatter: "checkbox", formatoptions: {disabled : false} , ...
To answer your second question, you will have to setup an event handler for the checkboxes, such that when one is clicked a function is called to, for example, send an AJAX POST to the server. Here is some example code to get you started. You can add this to the loadComplete event:
// Assuming check box is your only input field:
jQuery(".jqgrow td input").each(function(){
jQuery(this).click(function(){
// POST your data here...
});
});
This is an old one but has a lot of view so I decided to add my solution here too.
I'm making use of the .delegate function of JQuery to create a late binding implementation that will free you from the obligation of using the loadComplete event.
Just add the following:
$(document).delegate('#myGrid .jqgrow td input', 'click', function () { alert('aaa'); });
This will late bind that handler to every checkbox that's on the grid rows.
You may have a problem here if you have more than one checkbox column.
I had the same problem and I suppose that I found a good solution to handle checkbox click immediately. The main idea is to trigger editCell method when user clicks on the non-editable checkbox. Here is the code:
jQuery(".jqgrow td").find("input:checkbox").live('click', function(){
var iRow = $("#grid").getInd($(this).parent('td').parent('tr').attr('id'));
var iCol = $(this).parent('td').parent('tr').find('td').index($(this).parent('td'));
//I use edit-cell class to differ editable and non-editable checkbox
if(!$(this).parent('td').hasClass('edit-cell')){
//remove "checked" from non-editable checkbox
$(this).attr('checked',!($(this).attr('checked')));
jQuery("#grid").editCell(iRow,iCol,true);
}
});
Except this, you should define events for your grid:
afterEditCell: function(rowid, cellname, value, iRow, iCol){
//I use cellname, but possibly you need to apply it for each checkbox
if(cellname == 'locked'){
//add "checked" to editable checkbox
$("#grid").find('tr:eq('+iRow+') td:eq('+iCol+') input:checkbox').attr('checked',!($("#regions").find('tr:eq('+iRow+') td:eq('+iCol+') input:checkbox').attr('checked')));
//trigger request
jQuery("#grid").saveCell(iRow,iCol);
}
},
afterSaveCell: function(rowid, cellname, value, iRow, iCol){
if(cellname == 'locked'){
$("#grid").find('tr:eq('+iRow+') td:eq('+iCol+')').removeClass('edit-cell');
}
},
Then your checkbox will send edit requests every time when user clicks on it.
I have one submit function that sends all grid rows to webserver.
I resolved this problem using this code:
var checkboxFix = [];
$("#jqTable td[aria-describedby='columnId'] input").each(function () {
checkboxFix.push($(this).attr('checked'));
});
Then I mixed with values got from the code below.
$("#jqTable").jqGrid('getGridParam', 'data');
I hope it helps someone.
I had shared a full code at the link below, you can take a look if you need it.
http://www.trirand.com/blog/?page_id=393/bugs/celledit-checkbox-needs-an-enter-pressed-for-saving-state/#p23968
Better solution:
<script type="text/javascript">
var boxUnformat = function ( cellvalue, options, cell ) { return '-1'; },
checkboxTemplate = {width:40, editable:true,
edittype: "checkbox", align: "center", unformat: boxUnformat,
formatter: "checkbox", editoptions: {"value": "Yes:No"},
formatoptions: { disabled: false }};
jQuery(document).ready(function($) {
$(document).on('change', 'input[type="checkbox"]', function(e){
var td = $(this).parent(), tr = $(td).parent(),
checked = $(this).attr('checked'),
ids = td.attr('aria-describedby').split('_'),
grid = $('#'+ids[0]),
iRow = grid.getInd(tr.attr('id'));
iCol = tr.find('td').index(td);
grid.editCell(iRow,iCol,true);
$('input[type="checkbox"]',td).attr('checked',!checked);
grid.saveCell(iRow,iCol);
});
});
</script>
In your colModel:
...
{name:'allowAccess', template: checkboxTemplate},
...

Categories