Using jQGrid and jQUery tabs how to oprimize the number of grids - asp.net-mvc-3

I have 3 different tabs where i am displaying data using jQGrids(each tab contain one grid).
But i just thought that my grids are completely the same, only the difference is that they using different url to get data.
So I have three similar girds on each tab only with different urls:
First: url: '/Home/GetData?id=1' Second: url: '/Home/GetData?id=2' and Third: url: '/Home/GetData?id=3'
So i was thinking that may be i may declare grid only once and than on each tab click a can pass the url to load data? So on each tab click jQGrid will be populating from the new url.
May be some one may have any ideas about that?
Or may be some one may have better ideas how to reduce "jQGrid copy-paste" in that case?
UPDATE 0:
Nearly get it work i mean it is working but there is one small problem,
When i am switching tabs the header of the grid getting lost...and some jqgrid formatting as well.
here is my code:
$("#tabs").tabs({
show: function (event, ui) {
if (ui.index == 0) {
//$("#Grid1").appendTo("#tab1");
//$("#Grid1Pager").appendTo("#tab1");
//When Appending only pager and grid div, header getting lost so i've append the whole grid html instead
$("#gbox_Grid1").appendTo("#tab1");
changeGrid("#Grid1", 1);
}
else if (ui.index == 1) {
//$("#Grid1").appendTo("#tab2");
//$("#Grid1Pager").appendTo("#tab2");
$("#gbox_Grid1").appendTo("#tab2");
changeGrid("#Grid1", 2);
}
else if (ui.index == 2) {
//$("#Grid1").appendTo("#tab3");
//$("#Grid1Pager").appendTo("#tab3");
$("#gbox_Grid1").appendTo("#tab3");
changeGrid("#Grid1", 3);
}
}
});
function changeGrid(grid, id) {
$(grid).jqGrid('setGridParam', {
url: '/Home/GetData?id=' + id
});
$(grid).trigger('reloadGrid');
}
UPDATE 1
All right, i've changed the code to append the whole grid instead of appending grid div and pager only. So it is working like that.

You can basically make the tabs as regular buttons that will call some function which sets new URL parameter to the grid and reloads it.
The function should be something like this:
function changeGrid(grid, id) {
$(grid).jqGrid('setGridParam', {
url: '/Home/GetData?id=' + id, page: 1
});
$(grid).trigger('reloadGrid');
}
Note that I set the page to 1. Keep in mind that you might need to set the default sorting column or something similar depending on your solution.
UPDATE
If you really want to go with the tabs, the 'show' event handler can be simplified.
Try this:
$("#tabs").tabs({
show: function (event, ui) {
var id = ui.index + 1;
$("#gbox_Grid1").appendTo("#tab" + id);
$("#Grid1").jqGrid('setGridParam', {
url: '/Home/GetData?id=' + id
});
$("#Grid1").trigger('reloadGrid');
}
});

Related

jQuery autocomplete styling on only certain results

Is it possible to add styling to only some of the results returned in an autocomplete dropdown?
The code below works fine, however, I would like to style the individual results based on the value of data[x].restricted. When it is true, I still want to display those items but disable or grey them out within the autocomplete dropdown list. If data[x].restricted is false then I do not want to apply any additional styling to those items.
source: function (request, response) {
$.ajax({
url: $("#AutoCompleteCustomerNameUrl").val(),
type: "POST",
dataType: "json",
data: {
srchCus: request.term
},
success: function (data) {
var x, array = [];
for (x in data) {
array.push({
label: (data[x].restricted ? 'Restricted Access - ' : '') + data[x].customerName,
name: data[x].customerFullName
});
}
}
});
}
Any assistance on how to accomplish this would be much appreciated.
Approach 1 (feels hacky)
This doesn't feel like a great option, but you could probably do this by using jQuery to target elements based on their text content. Autocomplete suggestions are generated as <li>s, so something like this might work:
$('li:contains("Restricted Access")').addClass('grey');
The question is then when to run that? Those elements are added dynamically of course, after page load, so that would have to run after they've been created - you'd have to run it based on some autocomplete event. Looking through the list in the docs, maybe the open event would be best. A handler for that event will run whenever the menu is opened, so it could add a CSS class to all the just-created suggestions matching that selector. Eg (untested):
$("#selector").autocomplete({
// ... your normal autocomplete code ...
open: function(event, ui) {
// Add a CSS class to those suggestions matching the text
$('li:contains("Restricted Access")').addClass('grey');
}
});
I haven't tested this, as it doesn't feel like the right approach. Below is a much better, tested and working option.
Approach 2 (feels good)
You can also do this using the _renderItem extension point. If you check the example they give there you can see it is the function which actually generates the HTML which shows up as your autocomplete suggestion. If we can customise that, we could do anything - eg check details of the item, add specific CSS classes, etc.
I don't find those docs super clear, but it isn't hard to find examples of it in use, eg the Custom Data example (that #Simon-K linked to in the comments above) shows how to use it:
$("#selector").autocomplete({
// ... your normal autocomplete code ...
}).autocomplete("instance")._renderItem = function(ul, item) {
// Here we have complete control of what is returned, and access to
// the items!
return $("<li>").append("<div>" + item.label ...).appendTo(ul);
};
So with your requirements, we could do something like this:
$("#selector").autocomplete({
// ... your normal autocomplete code ...
}).autocomplete("instance")._renderItem = function(ul, item) {
var style = (item.restricted) ? 'grey' : '';
return $("<li>")
.append("<div class='" + style + "'>" + item.label + "</div>")
.appendTo(ul);
};
And then of course add a CSS class to style those items:
.grey {
color: #ccc;
}
Working JSFiddle.

Assigning behavior to Fine-Uploader generated thumbs

I think I have almost the same problem as described here : fine-uploader generate more unique custom file ids
But I can't figure out a solution that fit my needs.
I have a modal window containing 2 tabs. Each tab contains a FineUploader instance. That works pretty well.
BUT
I want to assign a behavior to each file added (for exemple, assign an "onclick" behavior to a generated thumb).
To do this, I do something like this :
callbacks: {
onComplete: function(id, name, response) {
scope.thumbloaded({
id: id,
name: name,
uuid: response.uuid
});
},
And the scope.thumbloaded function do this :
function thumbloaded(id, name, uuid) {
$('#qq-file-id-' + id).on('click', function(e) {
e.stopPropagation(); // avoid the entire thumbnail to catch the event
doSomething();
});
}
The problem is that FU creates DOM elements with formatted ids, like qq-file-id-XXX.
So, when I add several files in one of each FU instance I have (in each of my tabs, remember?), FU creates two DOM elements with same ids. And the "click" event is added twice on elements with same ids.
Do you see the problem??
I wasn't able to find a solution yet.
Any help?
thanks.
Ok, I finally find out a workaround, based on jquery's selector.
Very easy though.
I just apply a certain class to each of element I just took care of. Though, I don't hook new event listener to elements that already have it.
The code will speak for itself:
function thumbloaded(id, name, uuid) {
var newThumb = $('.qq-file-id-' + id + ':not(.aw-thumbnail)');
newThumb.prop('id', uuid);
$('#' + uuid).on('click', function(e) {
doSomething();
});
$('#' + uuid).addClass('aw-thumbnail');
}

Add or trigger event after inner content to page

I have links on a table to edit or delete elements, that elements can be filtered. I filtered and get the result using ajax and get functions. After that I added (display) the result on the table using inner.html, the issue here is that after filtering the links on the elements not work, cause a have the dojo function like this
dojo.ready(function(){
dojo.query(".delete-link").onclick(function(el){
var rowToDelete = dojo.attr(this,"name");
if(confirm("Really delete?")){
.......
}
});
I need to trigger the event after filtering, any idea?
(I'm assuming that you're using Dojo <= 1.5 here.)
The quick answer is that you need to extract the code in your dojo.ready into a separate function, and call that function at the end of your Ajax call's load() callback. For example, make a function like this:
var attachDeleteEvents = function()
dojo.query(".delete-link").onclick(function(el){
var rowToDelete = dojo.attr(this,"name");
if(confirm("Really delete?")){
.......
}
});
};
Then you call this function both in dojo.ready and when your Ajax call completes:
dojo.ready(function() { attachDeleteEvents(); });
....
var filter = function(someFilter) {
dojo.xhrGet({
url: "some/url.html?filter=someFilter",
handleAs: "text",
load: function(newRows) {
getTableBody().innerHTML = newRows;
attachDeleteEvents();
}
});
};
That was the quick answer. Another thing that you may want to look into is event delegation. What happens in the code above is that every row gets an onclick event handler. You could just as well have a single event handler on the table itself. That would mean there would be no need to reattach event handlers to the new rows when you filter the table.
In recent versions of Dojo, you could get some help from dojo/on - something along the lines of:
require(["dojo/on"], function(on) {
on(document.getElementById("theTableBody"), "a:click", function(evt) {...});
This would be a single event handler on the whole table body, but your event listener would only be called for clicks on the <a> element.
Because (I'm assuming) you're using 1.5 or below, you'll have to do it a bit differently. We'll still only get one event listener for the whole table body, but we have to make sure we only act on clicks on the <a> (or a child element) ourselves.
dojo.connect(tableBody, "click", function(evt) {
var a = null, name = null;
// Bubble up the DOM to find the actual link element (which
// has the data attribute), because the evt.target may be a
// child element (e.g. the span). We also guard against
// bubbling beyond the table body itself.
for(a = evt.target;
a != tableBody && a.nodeName !== "A";
a = a.parentNode);
name = dojo.attr(a, "data-yourapp-name");
if(name && confirm("Really delete " + name + "?")) {
alert("Will delete " + name);
}
});
Example: http://fiddle.jshell.net/qCZhs/1/

How to enable click in edit action button if new row is saved jqgrid

Edit formatter action button is placed to jqgrid column:
colModel: [{"fixed":true,"label":" change ","name":"_actions","width":($.browser.webkit == true? 37+15: 32+15)
,"align":"center","sortable":false,"formatter":"actions",
"formatoptions":{"keys":true,"delbutton":false,"onSuccess":function (jqXHR) {actionresponse = jqXHR;return true;}
,"afterSave":function (rowID) {
cancelEditing($('#grid'));afterRowSave(rowID,actionresponse);actionresponse=null; }
,"onEdit":function (rowID) {
if (typeof (lastSelectedRow) !== 'undefined' && rowID !== lastSelectedRow)
cancelEditing($('#grid'));
lastSelectedRow = rowID;
}
}}
New row is added to jqgrid in loadcomplete event
var newRowData = {};
var newRowId = '_empty' + $.jgrid.randId();
$('#grid').jqGrid('addRowData', newRowId, newRowData);
and its id is updated if save action button is clicked:
function aftersavefunc(rowID, response) {
restoreActionsIcons();
$('#grid').jqGrid('resetSelection');
var json = $.parseJSON(response.responseText);
$("#" + rowID).attr("id", json.Id);
lastSelectedRow = json.Id;
$("#grid").jqGrid('setSelection', lastSelectedRow);
}
After clicking save action button edit action button clicks are ignored. It is not possible to re-enter to edit mode after first editing.
How to fix this so that row can edited by edit button click again after saving ?
Update
I added $(this).focus() as suggested in Oleg answer and also wrapped id change into setTimeout as Oleg recommends in other great answer:
function aftersavefunc(rowID, response) {
restoreActionsIcons();
$(this).focus();
$('#grid').jqGrid('resetSelection');
var json = $.parseJSON(response.responseText);
setTimeout(function () {
$("#" + rowID).attr("id", json.Id);
lastSelectedRow = json.Id;
$("#grid").jqGrid('setSelection', lastSelectedRow);
}, 50);
}
Problem persists. The problem may related to row id change since:
It occurs only in last row (where id is changed after save). It does not occur for saved rows where responseText returns same id and row id is actually not changed.
It does not occur if cancel action button is pressed.
Maybe row id needs additional reset id addition to resetSelection or needs updated in somewhere other place also.
Update2
I added code form updated answer to errorfunc and used only english characters and numbers id ids. This allows to click multiple times but introduces additional issue:
extraparam is no more passed. If rowactions() calls are commented out, extraparam is passed with with rowactions calls extraparam is not passed.
I changed jqGrid source code and added alert to rowactions method:
alert( cm.formatoptions);
if (!$.fmatter.isUndefined(cm.formatoptions)) {
op = $.extend(op, cm.formatoptions);
}
In first clicks alert outputs 'Object'. In succeeding clicks to Save button it outputs undefined. So for unknown reason formatoptions is cleared.
Remarks to comment:
Absolute url in testcase is not used. Datasource is set to localarray.
I verified that testcase works in IE and FF without external url access.
For extraparam issue I can create new testcase.
Without image directory buttons are shown in cursor is moved over them.
Missing image directory still allows to reproduce the issue.
FormData function is defined in js file.
Since new issue occurs after adding rowactions() calls and does not occur if those calls are removed, this seems to be related to the code proposed in answer.
I suppose that the problem exist because one hide a button which has currently focus. Look at the code from the answer. If one remove the line $(this).focus(); // set focus somewhere one has the same problem as you describes. So I suggest that you just try to set somewhere, for example in restoreActionsIcons the focus to any the table element of the grid after hiding the button having currently the focus. I can't test this, but I hope it will help.
UPDATED: I examined your problem one more time and I hope I can suggest you a solution.
You problem can be divided on two sub-problems. The main your problem is the the changing of the id of the row. So it is not common problem which everybody has.
The problem is that "actions" formatter create onclick functions directly in the HTML code (see for example here):
ocl = "onclick=$.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','edit',"+opts.pos+");..."
So the functions will contains the original rowid. To fix the problem you can modify the code fragment of your aftersavefunc inside of setTimeout from
$("#" + rowID).attr("id", json.Id);
lastSelectedRow = json.Id;
$("#grid").jqGrid('setSelection', lastSelectedRow);
to something like the following:
var $tr = $("#" + rowID),
$divEdit = $tr.find("div.ui-inline-edit"),
$divDel = $tr.find("div.ui-inline-del"),
$divSave = $tr.find("div.ui-inline-save"),
$divCancel = $tr.find("div.ui-inline-cancel");
$tr.attr("id", json.Id);
if ($divEdit.length > 0) {
$divEdit[0].onclick = function () {
$.fn.fmatter.rowactions(newId,'grid','edit',0);
};
}
if ($divDel.length > 0) {
$divDel[0].onclick = function () {
$.fn.fmatter.rowactions(newId,'grid','del',0);
};
}
if ($divSave.length > 0) {
$divSave[0].onclick = function () {
$.fn.fmatter.rowactions(newId,'grid','save',0);
};
}
if ($divCancel.length > 0) {
$divCancel[0].onclick = function () {
$.fn.fmatter.rowactions(newId,'grid','cancel',0);
};
}
lastSelectedRow = json.Id;
$("#grid").jqGrid('setSelection', lastSelectedRow);
The second problem is that you use special characters inside of ids. I found a bug in the $.fn.fmatter.rowactions which need be fixed to support special characters in ids. The problem is that in the line 407 of jquery.fmatter.js the original rowid parameter rid will be changed:
rid = $.jgrid.jqID( rid )
and later everywhere will be used modified id. For example in the id is my.id the encoded version will be my\\.id. It's correct for the most places of the $.fn.fmatter.rowactions code (see here), but it' s incorrect as the rowid parameter of the editRow, saveRow, restoreRow, delGridRow, setSelection and editGridRow (see the lines 433-453). So the code must be fixed to use the original not escaped (not encoded) rid value with which the $.fn.fmatter.rowactions was called.
I think I will post tomorrow the corresponding bug report with the suggestions in the trirand forum.
UPDATED 2: The code $.fn.fmatter.rowactions(newId,'grid','edit',0); which I wrote above is just an example. I took it from the test demo which you send me. You should of course modify the code for your purpose. How you can see for example from the line the second parameter of the $.fn.fmatter.rowactions in the id of the grid which you use: 'grid', 'list' of something like myGrid[0].id. The last parameter should be the index of the column having formatter:'actions' in the colModel. You can use getColumnIndexByName function from the answer on your old question to get the index by column name.

jqGrid trigger "Loading..." overlay

Does anyone know how to trigger the stock jqGrid "Loading..." overlay that gets displayed when the grid is loading? I know that I can use a jquery plugin without much effort but I'd like to be able to keep the look-n-feel of my application consistent with that of what is already used in jqGrid.
The closes thing I've found is this:
jqGrid display default "loading" message when updating a table / on custom update
n8
If you are searching for something like DisplayLoadingMessage() function. It does not exist in jqGrid. You can only set the loadui option of jqGrid to enable (default), disable or block. I personally prefer block. (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options). But I think it is not what you wanted.
The only thing which you can do, if you like the "Loading..." message from jqGrid, is to make the same one. I'll explain here what jqGrid does to display this message: Two hidden divs will be created. If you have a grid with id=list, this divs will look like following:
<div style="display: none" id="lui_list"
class="ui-widget-overlay jqgrid-overlay"></div>
<div style="display: none" id="load_list"
class="loading ui-state-default ui-state-active">Loading...</div>
where the text "Loading..." or "Lädt..." (in German) comes from $.jgrid.defaults.loadtext. The ids of divs will be constructed from the "lui_" or "load_" prefix and grid id ("list"). Before sending ajax request jqGrid makes one or two of this divs visible. It calls jQuery.show() function for the second div (id="load_list") if loadui option is enable. If loadui option is block, however, then both divs (id="lui_list" and id="load_list") will be shown with respect of .show() function. After the end of ajax request .hide() jQuery function will be called for one or two divs. It's all.
You will find the definition of all css classes in ui.jqgrid.css or jquery-ui-1.8.custom.css.
Now you have enough information to reproduce jqGrid "Loading..." message, but if I were you I would think one more time whether you really want to do this or whether the jQuery blockUI plugin is better for your goals.
I use
$('.loading').show();
$('.loading').hide();
It works fine without creating any new divs
Simple, to show it:
$("#myGrid").closest(".ui-jqgrid").find('.loading').show();
Then to hide it again
$("#myGrid").closest(".ui-jqgrid").find('.loading').hide();
I just placed below line in onSelectRow event of JQ grid it worked.
$('.loading').show();
The style to override is [.ui-jqgrid .loading].
You can call $("#load_").show() and .hide() where is the id of your grid.
its is worling with $('div.loading').show();
This is also useful even other components
$('#editDiv').dialog({
modal : true,
width : 'auto',
height : 'auto',
buttons : {
Ok : function() {
//Call Action to read wo and
**$('div.loading').show();**
var status = call(...)
if(status){
$.ajax({
type : "POST",
url : "./test",
data : {
...
},
async : false,
success : function(data) {
retVal = true;
},
error : function(xhr, status) {
retVal = false;
}
});
}
if (retVal == true) {
retVal = true;
$(this).dialog('close');
}
**$('div.loading').hide();**
},
Cancel : function() {
retVal = false;
$(this).dialog('close');
}
}
});
As mentioned by #Oleg the jQuery Block UI have lots of good features during developing an ajax base applications. With it you can block whole UI or a specific element called element Block
For the jqGrid you can put your grid in a div (sampleGrid) and then block the grid as:
$.extend($.jgrid.defaults, {
ajaxGridOptions : {
beforeSend: function(xhr) {
$("#sampleGrid").block();
},
complete: function(xhr) {
$("#sampleGrid").unblock();
},
error: function(jqXHR, textStatus, errorThrown) {
$("#sampleGrid").unblock();
}
}
});
If you want to not block and not make use of the builtin ajax call to get the data
datatype="local"
you can extend the jqgrid functions like so:
$.jgrid.extend({
// Loading function
loading: function (show) {
if (show === undefined) {
show = true;
}
// All elements of the jQuery object
this.each(function () {
if (!this.grid) return;
// Find the main parent container at level 4
// and display the loading element
$(this).parents().eq(3).find(".loading").toggle(show);
});
return show;
}
});
and then simple call
$("#myGrid").loading();
or
$("#myGrid").loading(true);
to show loading on all your grids (of course changing the grid id per grid) or
$("#myGrid").loading(false);
to hide the loading element, targeting specific grid in case you have multiple grids on the same page
In my issues I used
$('.jsgrid-load-panel').hide()
Then
$('.jsgrid-load-panel').show()

Resources