jQuery button click refresh of jqGrid only firing once - javascript

I have the following jQuery code which I'm using to populate a jqGrid. It works perfectly posting to my ASP.NET MVC page on the first click of the button. My
problem is, any other clicks past the first it seems to run through the jquery code when clicking the button but it never makes it to the POST page. Any ideas why?
<script type="text/javascript">
$(document).ready(function() {
$('#btnSubmit').click(function() {
/* Refreshes the grid */
$("#list").jqGrid({
/* The controller action to get the grid data from */
url: '/CRA/AddPart',
data: { partNumber: "123"},
datatype: 'json',
mtype: 'GET',
/* Define the headers on the grid */
colNames: ['col1', 'col2', 'col3', 'col4'],
/* Define what fields the row columns come from */
colModel: [
{ name: 'col1', index: 'invid', width: 290 },
{ name: 'col2', index: 'invdate', width: 290 },
{ name: 'col3', index: 'amount', width: 290, align: 'right' },
{ name: 'col4', index: 'tax', width: 290, align: 'right'}],
height: 'auto',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
sortorder: "desc",
viewrecords: true,
imgpath: '../../Scripts/jgrid/themes/steel/images',
caption: 'Core Return Authorization Contents:',
cellEdit: true
});
});
});
</script>

The reason the grid isn't reloading is that you are calling the wrong method. The jqGrid method does approximately this:
Examine the table to see if it is already a grid; if so, exit.
Turn the table into a grid.
Populate the first page of data.
So the second time you call the method, it does nothing, as per step 1.
Instead, you should be calling $("#list").trigger("reloadGrid") on the second and all subsequent clicks.
Now, because of your mtype in the grid options, the grid is going to do a GET, not a POST. So if the POST is coming from the button itself (in other words, it is an input of type submit), you should return true to indicate that the submit should continue as usual.

Here is the solution :
<script type="text/javascript">
var firstClick = true;
$(document).ready(function() {
$('#btnSubmit').click(function() {
if (!firstClick) {
$("#list").trigger("reloadGrid");
}
firstClick = false;
/* Refreshes the grid */
$("#list").jqGrid({
/* The controller action to get the grid data from */
url: '/CRA/AddPart',
data: { partNumber: "123"},
datatype: 'json',
mtype: 'GET',
/* Define the headers on the grid */
colNames: ['col1', 'col2', 'col3', 'col4'],
/* Define what fields the row columns come from */
colModel: [
{ name: 'col1', index: 'invid', width: 290 },
{ name: 'col2', index: 'invdate', width: 290 },
{ name: 'col3', index: 'amount', width: 290, align: 'right' },
{ name: 'col4', index: 'tax', width: 290, align: 'right'}],
height: 'auto',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
sortorder: "desc",
viewrecords: true,
imgpath: '../../Scripts/jgrid/themes/steel/images',
caption: 'Core Return Authorization Contents:',
cellEdit: true
});
});
});
</script>

Because I need to POST new values to the the Action for me it does not work "reloadGrid".
I just remove all the content and create the empty table again.
In the if I check if the grid is there to hide the "empty chart" div (it shows just a message). In the else I just clean the div that surrounds the table and then I add inside the table again. When the plugin finds the empty table then it loads the grid completely again.
LoadTableData is the function that has the common functionality to create and load the grid.
Probably this solution is not elegant, but when the time is rushing...
$("#btnDownloadsPerFile").click(function () {
if ($('#chartContainerDownloadsPerFile .ui-jqgrid').length == 0) {
$('#chartContainerDownloadsPerFile .emptyChart').hide();
}
else {
$('#chartContainerDownloadsPerFile').empty();
$('#chartContainerDownloadsPerFile').append('<table id="downloadsPerFileGrid"></table>');
}
LoadTableData("downloadsPerFileGrid", $('#ddlportalOptionsDownloadsPerFile').val(), "downloadsPerFile", $('#ddlTimeOptionsDownloadsPerFile').val(), $('#ddlTimeValuesDownloadsPerFile').val(), $('#ddlCountries').val());
});

Related

JavaScript array push method not displaying all elements after pushing

I am working on a javascript array. I am getting a list from the backend of size 122. But I am pushing all the elements into a javascript array and displaying all of them in UI. But only 30 are visible in display.
I amusing JQGrid javascript frame work for grid display. Need some help to know what I am missing here. :(
Please find the code below:
var list= '<%=list%>';
alert(list.length);
for(i=0;i<list.length;i++){
list.push({'list':list[i] });
}
//alert gives me an expected answer (122) but in display only 30 are available.
//JQGRID CODE
jQuery("#jqGrid1").jqGrid({
datatype: "local",
data: list,
width : 600,
height: 600,
shrinkToFit: false,
forceFit: true,
colModel: [
{ label: 'List', name: 'list', index: 'list', width: 350, align: 'left', classes:'zeroBorderRight' }
],
gridComplete: function(){
jQuery('.ui-jqgrid-bdiv').css({'height':'auto', 'max-height':'100px'});
jQuery('.ui-th-column').css({'background':'#F2F2F2','height':'25px','text-align':'left'});
jQuery('.ui-jqgrid tr.jqgrow td').css({'height':'20px'});
$(this).find(">tbody>tr.jqgrow").removeClass("myAltRowClassEven myAltRowClassOdd");
$(this).find(">tbody>tr.jqgrow:odd").addClass("myAltRowClassEven");
$(this).find(">tbody>tr.jqgrow:even").addClass("myAltRowClassOdd");
$('.ui-corner-all').addClass('ui-zero-corner');
},
onSortCol: function (index, columnIndex, sortOrder) {
$(this).find(">tbody>tr.jqgrow").removeClass("myAltRowClassEven myAltRowClassOdd");
$(this).find(">tbody>tr.jqgrow:odd").addClass("myAltRowClassEven");
$(this).find(">tbody>tr.jqgrow:even").addClass("myAltRowClassOdd");
}
});

Push data to array populate jqGrid

Im try to populate my JQgrid with data each time I press the button "1" but I dont know what Im doing wrong. Im new to jquery. I have no problem printing the data to a p tag.
Im trying to use push should I use add instead? Or do I need to refresh the grid every press.
Any other suggested solutions are welcome.
$(document).ready(function () {
// Examle data for jqGrid
var currentTime = [
{time:""} ,
];
// Configuration for jqGrid Example 1
$("#table_list_1").jqGrid({
data: currentTime,
datatype: "local",
height: 250,
autowidth: true,
shrinkToFit: true,
rowNum: 14,
rowList: [10, 20, 30],
colNames: ['Time'],
colModel: [
{name: 'time', index: 'time', width: 60, sorttype: "double"},
],
pager: "#pager_list_1",
viewrecords: true,
caption: "Example jqGrid 1",
hidegrid: false
});
// Add responsive to jqGrid
$(window).bind('resize', function () {
var width = $('.jqGrid_wrapper').width();
$('#table_list_1').setGridWidth(width);
});
});
window.addEventListener('keydown', doKeyDown, false);
function doKeyDown(e){
if(e.keyCode == 49 & wavesurfer.isPlaying()){
// KEY = " 1 "
currentTime.push(wavesurfer.getCurrentTime());
});
}
}
My solution:
jQuery("#table_list_1").addRowData("1",{id: id, time: wavesurfer.getCurrentTime()});

jQGrid - "jpg1" instead of proper id number

I'm loading local file (I'm parsing csv file into json and then transfer the array to jqGrid). Table generated through jqGrid should allow user to modify, add and delete the data in the grid. Everything seemed to work perfectly until I wanted to add a row to my grid. One of the columns had a parameter key = true which is my id for the rows. When I try to add new row, the grid changes my id into jpg1. The others columns are fine. Below is the code I'm using:
$("#jqGrid").jqGrid({
datatype: "local",
data: myData,
editurl: "clientArray",
colModel: [
{
label: 'Kod',
name: 'Kod',
width: 60,
editable: true,
key: true,
sorttype: 'number'
},
{
label: 'Firma',
name: 'Firma',
width: 120,
editoptions:
{
size: 40,
sopt:['cn']
},
editable: true,
sorttype: 'string'
},
{
label: 'Adres',
name: 'Adres',
width: 80,
editoptions: {size: 40},
editable: true
},
{
label: 'Miasto',
name: 'Miasto',
width: 80,
editoptions:
{
size: 40,
sopt:['cn']
},
editable: true
}
],
height: 'auto',
autowidth: true,
shrinkToFit: false,
forceFit: false,
autoencode: true,
viewrecords: true,
caption: "Title",
pager: "#jqGridPager",
sortable: true,
ignoreCase: true,
sortname: 'Kod',
sortorder: 'asc',
rowNum: 5,
rowList: [5, 10, 20, "10000:All"],
ondblClickRow: function(rowid) {
$("#jqGrid").jqGrid('editGridRow', rowid,
{
editCaption: "The Edit Dialog",
zIndex:100,
recreateForm: true,
closeAfterEdit: true,
width: 900,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
}
});
$('#jqGrid').jqGrid('navGrid',"#jqGridPager",
{ edit: true, add: true, del: true, search: false, refresh: true, view: true, cloneToTop: true},
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
zIndex:100,
recreateForm: true,
closeAfterEdit: true,
reloadAfterSubmit: true,
width: 900,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
width: 900,
zIndex:100,
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dialog
delSettings,
// options for the Search Dialog
{
zIndex:100
},
// options for the View Dialog
{
width: '100%'
});
I'm attaching a screenshot that shows a problem:
Photo
The data I use is a file parsed into JSON array via Papaparse.js plugin.
EDIT:
I've added the test data if somebody would like to test the code.
var myData = [];
myData.push(
{
Kod: 1.1,
Firma: 'Hutchinson',
Adres: '5th Avenue',
Miasto: 'Wroclaw'
},
{
Kod: 2.1,
Firma: 'BMW',
Adres: '6th Avenue',
Miasto: 'Warsaw'
});
I will be grateful for any help.
If you need the grid only for local editing, you can consider just remove key: true property to solve the problem. It's the way, which I would recommend you. You can include id property in the input data which will be used as value of rowid (id of <tr> elements).
Alternatively you can change the block "options for the Add Dialog" to the following
// options for the Add Dialog
{
width: 900,
zIndex:100,
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: true,
onclickSubmit: function (options, postdata, frmoper) {
// save Kod in some other parameter
return {myKod: postdata.Kod};
},
afterSubmit: function (jqXHR,postdata, frmoper) {
// restore the correct value
postdata.Kod = postdata.myKod;
// inform jqGrid that it was not an error
return [true];
}
},
You still don't would be able to change the id of the row in the way.
By the way you wrote that you use jqGrid 4.7.1. I want remind you that jqGrid 4.7.0 is the last version which is free. It's the reason why I started free jqGrid project which still free. You can get it here (see readme and wiki).
The demo shows an example of the above code fixes using free jqGrid 4.8.

Get the key value of the row of whose cusstom button has been clicked

I found myself in need of what i guess should be a trivial requirement. i have a jqGrid in which i have added a custom button in each row. now i am able to associate a client side click event with it but i want to know the key value (Id) in my case of the row whose custom button was clicked, so that i can proceed with this id and do whatever i want to do.
My code for jqGrid is as below
jQuery("#JQGrid").jqGrid({
url: 'http://localhost:55423/JQGrid/JQGridHandler.ashx',
datatype: "json",
colNames: ['', 'Id', 'First Name', 'Created Date', 'Member Price', 'Non Member Price', 'Complete', 'customButton'],
colModel: [
{ name: '', index: '', width: 20, formatter: "checkbox", formatoptions: { disabled: false} },
{ name: 'Id', index: 'Id', width: 20, stype: 'text', sortable: true, key: true },
{ name: 'FirstName', index: 'FirstName', width: 120, stype: 'text', sortable: true },
{ name: 'CreatedDate', index: 'CreatedDate', width: 120, editable: true, sortable: true, hidden: true, editrules: { edithidden: true} },
{ name: 'MemberPrice', index: 'MemberPrice', width: 120, editable: true, sortable: true },
{ name: 'NonMemberPrice', index: 'NonMemberPrice', width: 120, align: "right", editable: true, sortable: true },
{ name: 'Complete', index: 'Complete', width: 60, align: "right", editable: true, sortable: true },
{ name: 'customButton', index: 'customButton', width: 60, align: "right" }
],
rowNum: 10,
loadonce: true,
rowList: [10, 20, 30],
pager: '#jQGridPager',
sortname: 'Id',
viewrecords: true,
sortorder: 'desc',
caption: "List Event Details",
gridComplete: function () {
jQuery(".jqgrow td input", "#JQGrid").click(function () {
//alert(options.rowId);
alert("Capture this event as required");
});
}
});
jQuery('#JQGrid').jqGrid('navGrid', '#jQGridPager',
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext:"Delete"
},
{/*EDIT EVENTS AND PROPERTIES GOES HERE*/ },
{/*ADD EVENTS AND PROPERTIES GOES HERE*/},
{/*DELETE EVENTS AND PROPERTIES GOES HERE*/},
{/*SEARCH EVENTS AND PROPERTIES GOES HERE*/}
);
Help or any pointers would be much appreciated.
The main solution of your problem in the following: you need include parameter, for example e, in the callback of click handle. The parameter has Event object type which contain target property. Alternatively you can use this in the most cases. Having e.target you can goes to the closest parent <tr> element. It's id is the value which you need:
jQuery(this).find(".jqgrow td input").click(function (e) {
var rowid = $(e.target).closest("tr").attr("id");
alert(rowid);
});
Additionally you should make some other modifications in your code to fix some bugs. The usage of
name: '', index: ''
is wrong in colModel. You should specify any non-empty unique name. For example name: 'mycheck'.
Next I recommend you to remove all index properties from colModel. If you use loadonce: true you have to use index properties with the same values as the corresponding name values. If you don't specify any index properties you will have smaller and better readable code. The corresponding values of index properties will be copied by jqGrid internally from the corresponding name values. In the same way you can remove properties like stype: 'text', sortable: true which values are default values (see Default column of the documentation)
The next problem is that you include probably HTML data in the JSON response from the server. (One can't see any formatter for customButton for example). It's not good. In the way you can have problems if the texts of the grid contains special HTML symbols. I find better to use pure data in JSON response from the server. One can use formatters, custom formatters etc on the client side. In the case one can use autoencode: true option of jqGrid which make HTML encoding of all texts displayed in the grid. In the way you will have more safe code which will don't allow any injection (for example no including of JavaScript code during editing of data).
Next remark: I don't recommend you to use gridComplete. The usage of loadComplete is better. See my old answer about the subject.
The last important remark. To handle click events on the buttons placed inside of grid one don't need to bind separate click handle to every button. Instead of that one can use one beforeSelectRow or onCellSelect callback. The answer and this one describe this. The answers use <a> in custom formatter, but <input> works exactly in the same way.
Another approach that can be used to retrieve the id of the row for which the custom button is clicked is by adding formatter to your custom button cloumn
{ name: 'customButton', index: 'customButton', width: 60, align: "right",
formatter: function ( cellvalue, options, rowObject ) {
return "<input type='button' class='custom-button' id='custom"+ rowObject.id +"'/>";
}
}
Now every button has the row id
$('input[id^="custom"]').click(function() {
var id = this.attr('id').replace("custom", ""); // required row ID
});

jqGrid Filter Toolbar - colModel: object is null or undefined problem

Actually creating a filter jqGrid toolbar should be straight ahead as in the "new in 3.5, integrated search toolbar" example or documentation.
However, when I run the line myDataTable.jqGrid('filterToolbar', filterOpts); I always get an error "Unable to get value of the property 'colModel': object is null or undefined" in line 3613 of JQuery.jqGrid.src.js, which is: $.each($t.p.colModel,function(i,n) { ..
Just for the record, version of jqGrid is 4.1.2. The grid itself display / works OK.
Here is the code how I init the grid, most likely I do oversee something very simple.
var ft = document.getElementById("myData"); // this is the HTML table element as usual
var colModel = [
{ name: 'i', index: 'i', width: 60, hidden: true, search: false },
{ name: 'c', index: 'c', width: 100, search: true },
{ name: 'p', index: 'p', width: 100, search: true },
{ name: 'displayed', index: 'displayed', align: 'center', width: 100, formatter: booleanToCheckmark, search: false },
];
$(function() {
$(ft).jqGrid({
datatype: 'clientSide',
data: globals.myData, // Array of objects ("the data"), data is correctly displayed
height: 300,
// autowidth: true,
width: 300,
forceFit: true,
colNames: ['I', 'C', 'P', 'dis.'],
colModel: colModel,
rowNum: 10000,
sortname: 'displayed',
sortorder: 'desc',
viewrecords: true,
gridview: true,
caption: 'XYZ'
});
});
// filter bar
// http://www.trirand.com/jqgridwiki/doku.php?id=wiki:toolbar_searching
var filterOpts = { autosearch: true };
// LINE WHERE IT FAILS
$(ft).jqGrid('filterToolbar', filterOpts);
The error that you try to call filterToolbar outside of $(function() {/*it should be called here*/}); block.
Typically one places all the code inside of $(function() {...});. In the way one reduces additionally the number of global variables which will be added as the properties to window. The usage of global variables increase additionally the probability to have conflicts with other standard global variables.

Categories

Resources