How to get hidden columns in jQGrid - jqgrid

jqGrid ('getGridParam', 'colModel') does not return the currently hidden columns.
colNames:[ ' Group Id ' ,'Group Title','No. of Participants','Comment','Date Of Creation','Last Modified'],
colModel:[
{name:'participant_group_id',index:'1',editrules:{required:false,email:false,number:false},search:true,width:0,key:true, hidden:true, editable:true,edittype:"text",editoptions: {size:30}},
{name:'participant_group_title',index:'2',formoptions:{elmprefix:'<font color="red">*</font>'},editrules:{required:true,email:false,number:false},search:true,width:150,key:false, hidden:false, editable:true,edittype:"text",editoptions: {size:30}},
{name:'number_of_group_participants',index:'3',editrules:{required:false,email:false,number:false},search:true,width:125,key:false, hidden:false, editable:false,edittype:"text",editoptions: {size:30}},
{name:'comment',index:'4',editrules:{required:false,email:false,number:false},search:true,width:135,key:false, hidden:false, editable:true,edittype:"textarea",editoptions: {rows:"5",cols:"28"}},
{name:'group_created_date_time',index:'5',editrules:{required:false,email:false,number:false},search:true,width:135,key:false, hidden:false, editable:false,edittype:"text",editoptions: {size:60}},
{name:'group_updated_date_time',index:'6',editrules:{required:false,email:false,number:false},search:true,width:120,key:false, hidden:false, editable:false,edittype:"text",editoptions: {size:60}}],
jqGrid ('getGridParam', 'colModel') returns the last 5 columns
colModel
(5) […]
​
0: Object { name: "participant_group_title", index: "2", search: true, … }
​
1: Object { name: "number_of_group_participants", index: "3", search: true, … }
​
2: Object { name: "comment", index: "4", search: true, … }
​
3: Object { name: "group_created_date_time", index: "5", search: true, … }
​
4: Object { name: "group_updated_date_time", index: "6", search: true, … }
​
length: 5
​
<prototype>: Array []
How to get the hidden column? Is there a way to get the details of the hidden column? Let me know of a mechanism to get the details of the hidden column.

Here is the code where I was fetching the Column Model from the jQGrid object and trying to identify the hidden columns so that they do not show up in the generated Excel. Note I am using a server-side solution here for generating the JSON from MySQL.
function exportToExcel(interface_id, part_id){
$.ajax({
type: "GET",
async: true,
url: "./interfaceenginev2.GetJSONforGrid",
data: "interface_id=" + interface_id + "&part_id=" + part_id,
success: function (data)
{
var colNames = $('#' + part_id).jqGrid ('getGridParam', 'colNames');
var colModel = $('#' + part_id).jqGrid ('getGridParam', 'colModel');
for( var i = 0; i < colModel.length; i++){
if ( colModel[i].hidden === true) {
var name = colModel[i].name;
delete data[i][name];
colNames.splice(i, 1);
colModel.splice(i, 1);
}
}
$.unblockUI();
var ws = XLSX.utils.json_to_sheet(data);
var range = XLSX.utils.decode_range(ws['!ref']);
for(var C = range.s.c; C <= range.e.c; ++C) {
var address = XLSX.utils.encode_col(C) + "1";
if(!ws[address]) continue;
ws[address].v = colNames[C];
}
var wscols = [];
colModel.forEach(function (column) {
wscols.push({wpx:column.width});
});
ws["!cols"] = wscols;
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, interface_id);
XLSX.writeFile(wb, part_id + ".xlsx" );
},
error: function (xhr) {
$.unblockUI();
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
}
This code is working now!

Related

Configuring jqgrid search to search one of many

I'm having trouble either understanding or implementing search/filter functionality in jqgrid.
The data set is returned to the client with each item having a list of designers:
"IAConsultWorkflowRequestsList": [
{
"AppID": "ISP",
"SubmittedDate": "12/13/2018",
"IAAssigned": "<a style='color:blue !important;' href='mailto:Joseph#somewhere.com'><u>Joseph Kraft</u></a>",
"IAAssignedName": null,
"Status": "In Discovery",
"SLA": 0,
"DaysPassed": 157,
"IsUserFM": false,
"IsUserSecureEnv": false,
"DesignParticipants": [
{
"Name": "John Kraft",
"EmailAddress": "",
"ID": "A2049"
},
{
"Name": "Zack Adamas",
"EmailAddress": "Zachary.Adamas#somewhere.com",
"ID": "U6696"
},
{
"Name": "David Kosov",
"EmailAddress": "David.Kosov#somewhere.com",
"ID": "U6644"
}
]
}
So in the 'Designers' column, I am concatenating the results to be comma separated, e.g.
John Kraft,
Zack Adamas,
David Kosov
And, if the item has an email address, the individual name is formatted as an email link:
<td role="gridcell" style="text-align:center;" title="John Kraft,Zack Burns,David Cosand" aria-describedby="workFlowIAGrid_DesignParticipants">
John Kraft,<br>
<a style="color:blue !important;" ref="mailto:Zachary#somewhere.com"><u>Zack </u></a>,<br>
<a style="color:blue !important;" href="mailto:David#somewhere.com"><u>David </u></a></td>
I have a select element with entries John, Zack, and David, but when I select one of the options, I do not get expected results. If I select David, I would like to be shown any rows that contain David as one of potentially several names in the Designer column.
However, I am getting erratic behavior. Some of the sopt options will cause something to happen, but not what is expected. None of the contains/not contained or in/not in options seem to do what I need. What am I doing wrong?
Per Tony's comment, here is the grid init code:
$gridEl.jqGrid({
xhrFields: {
cors: false
},
url: "/IAConsult/GetWorkFlowIARequests",
postData: {
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
datatype: "json",
crossDomain: true,
loadonce: true,
mtype: 'GET',
sortable: true,
viewrecords: true,
pager: '#workFlowIAGridPager',
multiselect: true,
rowNum: 50,
autowidth: true,
colModel: [
{ label: 'Design Participants', name: 'DesignParticipants', align: "center", formatter:commaSeparatedList },
//same for other columns...
],
beforeSelectRow: function (rowid, e) {
var $myGrid = $(this),
i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
cm = $myGrid.jqGrid('getGridParam', 'colModel');
return (cm[i].name === 'cb');
},
jsonReader: {
repeatitems: true,
root: "IAConsultWorkflowRequestsList"
},
beforeSubmitCell: function (rowid, name, value, iRow, iCol) {
return {
gridData: gridData
};
},
serializeCellData: function (postdata) {
return JSON.stringify(postdata);
},
gridComplete: function () {
rowCount = $gridEl.getGridParam('records');
gridViewRowCount = rowCount;
var rowIDs = $gridEl.getDataIDs();
var inCompleteFlag = false;
//Filter code to apply filter in headers in MyWork grid
var datatoFilter = $gridEl.jqGrid('getGridParam', 'lastSelectedData').length == 0
? $gridEl.jqGrid("getGridParam", "data")
: $gridEl.jqGrid('getGridParam', 'lastSelectedData');
var $grid = $gridEl, postfilt = "";
var getUniqueNames = function (columnName) {
var uniqueTexts = [],
mydata = datatoFilter,
texts = $.map(mydata, function(item) {
return item[columnName];
}),
textsLength = texts.length,
text = "",
textsMap = {},
i;
if (texts[0] && texts[0].Name)
texts = $.map(texts,
function(item) {
return item.Name;
});
for (i = 0; i < textsLength; i++) {
text = texts[i];
if (text !== undefined && textsMap[text] === undefined) {
// to test whether the texts is unique we place it in the map.
textsMap[text] = true;
uniqueTexts.push(text);
}
}
if (columnName == 'ConsultID') {
return (uniqueTexts.sort(function (a, b) { return a - b; }));
} else return uniqueTexts.sort();
}, buildSearchSelect = function (uniqueNames) {
var values = {};
values[''] = 'All';
$.each(uniqueNames,
function () {
values[this] = this;
});
return values;
}, setSearchSelect = function (columnName) {
var changedColumns = [];
this.jqGrid("setColProp",
columnName,
{
stype: "select",
searchoptions: {
value: buildSearchSelect(getUniqueNames.call(this, columnName)),
sopt: getSortOptionsByColName(columnName),
dataEvents: [
{
type: "change",
fn: function (e) {
setTimeout(function () {
//get values of dropdowns
var DesignParticipant = $('#gs_workFlowIAGrid_DesignParticipants').val();
//same for other columns...
var columnNamesArr = columns.split(',');
changedColumns.push(columnName);
for (i = 0; i < columnNamesArr.length; i++) {
if (true) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNamesArr[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNamesArr[i] + "']");
for (j = 0; j < un.length; j++) {
var val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
}
$('#gs_workFlowIAGrid_DesignParticipants').val(DesignParticipant);
//same for other columns...
},
500);
//setting the values :
}
}
]
}
});
};
function getSortOptionsByColName(colName) {
console.log(colName);
if (colName === 'DesignParticipants')
return ['in'];
else
return ['eq'];
}
setSearchSelect.call($grid, "DesignParticipants");
//same for other columns...
$grid.jqGrid("filterToolbar",
{ stringResult: true, searchOnEnter: true });
var localFilter = $gridEl.jqGrid('getGridParam', 'postData').filters;
if (localFilter !== "" && localFilter != undefined) {
globalFilter = localFilter;
}
$gridEl.jqGrid("setGridParam",
{
postData: {
"filters": globalFilter,
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
search: true,
forceClientSorting: true
})
.trigger("reloadGrid");
//Ending Filter code
var columnNamesArr = columns.split(',');
for (i = 0; i < columnNamesArr.length; i++) {
if (true) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNamesArr[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNamesArr[i] + "']");
for (j = 0; j < un.length; j++) {
val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
}
},
// all grid parameters and additionally the following
loadComplete: function () {
$gridEl.jqGrid('setGridWidth', $(window).width(), true);
$gridEl.setGridWidth(window.innerWidth - 20);
},
height: '100%'
});
Here is the formatter I am using on the column:
function commaSeparatedList(cellValue, options, rowdata, action) {
let dps = [];
_.forEach(cellValue, function (item) {
let formatted = '';
if (item.EmailAddress)
formatted += '<a style="color:blue !important;" href="mailto:' +
item.EmailAddress +
'"><u>' +
item.Name +
'</u></a>';
else formatted = item.Name;
dps.push(formatted + ',<br/>');
});
let toString = dps.join('');
return toString.substring(0,toString.length-6);
}
And then the only other pertinent thing is that I used a function to return 'in' (or some other key - these are the options I said weren't apparently working in the initial post) if the column is named 'Design Participants', else equal for any other column:
setSearchSelect = function (columnName) {
var changedColumns = [];
this.jqGrid("setColProp",
columnName,
{
stype: "select",
searchoptions: {
value: buildSearchSelect(getUniqueNames.call(this, columnName)),
sopt: getSortOptionsByColName(columnName),
dataEvents: [
{...
function getSortOptionsByColName(colName) {
console.log(colName);
if (colName === 'DesignParticipants')
return ['in'];
else
return ['eq'];
}
The issue was that the underlying data (the DesignParticipants in the returned JSON above) did not match the selected string, since the data itself was an array. I believed the filtering was based on the displayed text in the grid table, but, it was based on the underlying data. So, I created a new property of the returned JSON that was a string, and the filtering worked as expected.

Create Jqgrid pass value from datatable and change column names dynamically

I want to create jqgrid by passing value from Datatable as I have multiple tables ,based on that I need to change colomn names dynamically,in asp.net mvc.
Hi after working hard on it finally i have got a solution.
<table id="tableDetails1" cellpadding="0" cellspacing="0">
<tr><td></td></tr></table>
<div id="pager" style="text-align: center"></div>
Jqgrid and javascript function
<script type="text/javascript">
$(document).ready(function () {
// $("#tableDetails1").GridUnload();
CreateColumnDetails();
});
function getData() {
debugger;
$.ajax({
url: '#Url.Action("TableDetails", "TableInfo")',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger;
var obj = $.parseJSON(result);
resultData = JSON.parse(result);
$(resultData).each(function (e) {
$("#tableDetails1").addRowData(e, this);
});
}
});
}
function CreateColumnDetails() {
debugger;
$.ajax({
url: '#Url.Action("GetColumnDetails", "TableInfo")',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
var colName = JSON.parse(result);
debugger;
var colModels = BuildColumnModel(colName);
$("#tableDetails1").jqGrid({
url: '#Url.Action("GetColumnDetails", "TableInfo")',
datatype: 'json',
colNames: colName,
colModel: colModels
})
}
});
getData();
}
function CreateGrid(result) {
debugger;
$("#tableDetails1").jqGrid({
url: '#Url.Action("TableDetails", "TableInfo")',
datatype: 'json',
mtype: 'Get',
pager: $('#pager'),
rowNum: 5,
gridview: true,
rowList: [5, 10, 20, 30],
height: '100%',
viewrecords: true,
caption: 'Table Details ',
emptyrecords: 'No Records found',
jsonReader: {
root: function (rows) {
debugger;
return typeof rows === "string" ? $.parseJSON(rows) : rows;
},
page: 'page',
total: 'total',
records: 'records',
repeatitems: false,
id: "0"
},
autowidth: true,
multiselect: false,
loadError: function (jqXHR, textStatus, errorThrown) {
debugger;
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
}).navGrid('pager', { edit: false, add: false, del: false });
}
function BuildColumnModel(result) {
// var uFields = result.split(',');
var uFields = result;
var columns = [];
for (var i = 0; i < uFields.length ; i++) {
if (uFields[i].indexOf('Id') > -1) {
columns.push({ name: uFields[i], index: uFields[i], key: true });
//columns.push({ 'name': name, 'index': name, key: true});
}
// else if (uFields[i].indexOf('Name') > -1) {
else if(uFields[i].length>-1){
columns.push({ name: uFields[i], index: uFields[i]})
// columns.push({ 'name': name, 'index': name });
}
//else if (uFields[i].length > -1) {
// columns.push({ name: uFields[i], index: uFields[i]})
// //columns.push({ 'name': name, 'index': name, key: true });
//}
}
return columns;
}
</script>
Controllers
**Httppost method adding rows dynamically
[HttpPost]
public ActionResult TableDetails(int? id, DataTable dt)
{
dt = new DataTable();
dt = GetTableDetails(id);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
serializer.Serialize(col.ColumnName);
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return Json(serializer.Serialize(rows), JsonRequestBehavior.AllowGet);
}
Column Details in string format
[HttpPost]
public ActionResult GetColumnDetails(int ? id, DataTable dt)
{
dt = GetTableDetails(1);
// id = (int)Session["id"] ;
// dt = GetTableDetails(id);
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return Json(serializer.Serialize(columnNames), JsonRequestBehavior.AllowGet);
}

processing return from ajax call

I'm using the twitter-bootstrap's typeahead to do autocompletion on an input field.
What I have so far:
$(".airportSearch").typeahead({
source: function(typeahead, query) {
$.ajax({
url: url_,
dataType: "json",
data: {
n: 12,
q: typeahead
},
success: function(data) {
var return_list = [], i = data.length;
while(i--) {
return_list[i] = {
type: data[i].type,
id: data[i].iata,
value: data[i].city,
returnvalue: data[i].type == 'city' ? data[i].city + ' [' + data[i].iata + ']' :
data[i].city + ' (' + data[i].iata + ')'
};
}
}
});
}
});
example of output:
[{"type":"airport","city":"Quebec","airport":"Quebec","iata":"YQB","country":"Canada","locationId":"airport_YQB"},
{"type":"airport","city":"Queenstown","airport":"Queenstown","iata":"ZQN","country":"New Zealand","locationId":"airport_ZQN"},
{"type":"city","city":"Setif","airport":"All Airports","iata":"QSF","country":"Algeria","locationId":"DZ_city_QSF"},
{"type":"airport","city":"Setif","airport":"Setif","iata":"QSF","country":"Algeria","locationId":"airport_QSF"},
{"type":"airport","city":"QachaS Nek","airport":"QachaS Nek","iata":"UNE","country":"Lesotho","locationId":"airport_UNE"},
{"type":"airport","city":"Qaisumah","airport":"Qaisumah","iata":"AQI","country":"Saudi Arabia","locationId":"airport_AQI"}]
I have logged the return_list variable that I create and have confirmed that it is the expected list of objects I have created. I want to populate the autocomplete options with the returnvalue strings in the list of objects.
Could anyone tell me how, or point me to somewhere that tells me how?
Try this:
$(".airportSearch").typeahead({
source: function(typeahead, process) {
return $.ajax({ // return ajax result
url: url_,
dataType: "json",
data: {
n: 12,
q: typeahead
},
success: function(data) {
var return_list = [], i = data.length, data_vals = []; // add data_vals array for typeahead
while(i--) {
return_list[i] = {
type: data[i].type,
id: data[i].iata,
value: data[i].city,
returnvalue: data[i].type == 'city' ? data[i].city + ' [' + data[i].iata + ']' :
data[i].city + ' (' + data[i].iata + ')'
};
data_vals.push(return_list[i].returnvalue); // populate the needed values
}
return process(data_vals); // and return to typeahead
}
});
}
});
Normally I would populate the data_vals for typeahead only but you did it your way for your reason I guess.
Hope it helps.

google maps and ajax

Is it possible to return a variable, more specifically an array of values or a string from an $.ajax call. I currently understand that this can't be done... i.e. $.ajax responses need to be added to the DOM immediately. Please correct me if I am missing something obvious here.
var infoWindow;
var tableID = 'atableID';
var str;
var beachID;
var beach_location;
var beach_region;
/* start map initialization */
function initialize() {
latlng = new google.maps.LatLng(49.894634, -97.119141);
var myOptions = {
center: latlng,
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
mapTypeControlOptions: {
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.SATELLITE,
google.maps.MapTypeId.HYBRID,
google.maps.MapTypeId.TERRAIN
],
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
overviewMapControl: true,
overviewMapControlOptions: {
opened: true
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
layer = new google.maps.FusionTablesLayer({
query: {
select: 'Point',
from: atableID
},
suppressInfoWindows: true
});
layer.setMap(map);
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(layer, 'click', function (e) {
// close infoWindow if open
if (infoWindow) {
infoWindow.close();
}
beachID = e.row['Beach_ID'].value;
beach_location = e.row['Beach_Location'].value; ;
beach_region = e.row['Beach_Region'].value;;
//console.log(beachID);
// get data set
getEcoliData(beachID,beach_location,beach_region);
getAlgaeData(beachID,beach_location,beach_region);
}); // end google.maps.addListener
} // end map initialization
function getEcoliData(beachID,beach_location,beach_region) {
//local namespace
var rows = [];
var ecoliTable;
var items = [];
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=a key value=?';
var whereClause = "WHERE 'Beach_ID' = " + beachID;
var query = "SELECT 'Sample_Date', 'Average_E._coli_Density','Recreational_Water_Quality_Guideline' FROM atblid " + whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
$.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp',
success: function (data) {
rows = data.rows;
// empty table
//$('#content_placeholder').empty();
//$('.ecoli_table').remove();
$('#ecoli_heading').empty();
$('#content_placeholder').prepend('<h6 id="ecoli_heading">E.Coli Data</h6>')
.append('<p>' + beach_location + '</p>').append('<p>' + beach_region + '</p>');
$('.ecoli_table').append('<tr>'
+ '<th>Sample Date</th>'
+ '<th>Average E.Coli Density</th>'
+ '<th>Recreational Water Quality Guideline</th>'
+ '</tr>');
for (var i = 0; i < rows.length; i++) {
//items.push(rows[i]);
$('.ecoli_table tr:first').after('<tr><td>' + rows[i].join('</td><td>') + '</td></tr>');
}
if (typeof ecoliTable == 'undefined') {
// dataTables
ecoliTable = $(".ecoli_table").dataTable({
"sPaginationType": "full_numbers",
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"aaSorting": [[0, "desc"]],
"bDestroy": true,
"aoColumns": [
{ "sTitle": "Sample_Date" },
{ "sTitle": "Average_E._coli_Density" },
{ "sTitle": "Recreational_Water_Quality_Guideline" }
]
});
} else {
//ecoliTable.fnDestroy();
$(".ecoli_table > tbody").empty();
ecoliTable.fnDraw();
//$('.ecoli_table').find("tr:gt(0)").remove();
}
},
error: function () {
alert("Data is not available for this location at the present time, please check back at a later time. Thank you.");
}
});
}
function getAlgaeData(beachID,beach_location,beach,region) {
//local namespace
var rows = [];
var algaeTable;
var items = [];
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=apikey&callback=?';
var whereClause = "WHERE 'Beach_ID' = " + beachID;
var query = "SELECT 'Sample_Date','Algal_Toxin_Microcystin','Recreational_Guideline_20','Blue_Green_Algae_Cells','Recreational_Guideline' FROM tableid " + whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
$.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp',
success: function (data) {
rows = data.rows;
// empty table
//$('#content_placeholder').empty();
//$('.algae_table').remove();
$('#algae_heading').empty();
$('.ecoli_table').after('<h6 id="algae_heading">Algae Data</h6>');
$('.algae_table').append('<tr>'
+ '<th>Sample Date</th>'
+ '<th>Algal_Toxin_Microcystin</th>'
+ '<th>Recreational_Guideline_20</th>'
+ '<th>Blue_Green_Algae_Cells</th>'
+ '<th>Recreational_Guideline</th>'
+ '</tr>');
for (var i = 0; i < rows.length; i++) {
//items.push(rows[i]);
$('.algae_table tr:first').after('<tr><td>' + rows[i].join('</td><td>') + '</td></tr>');
}
if (typeof algaeTable == 'undefined') {
//algae
algaeTable = $(".algae_table").dataTable({
"sPaginationType": "full_numbers",
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"bDestroy": true,
"aaSorting": [[0, "desc"]],
"aoColumns": [
{ "sTitle": "Sample_Date" },
{ "sTitle": "Algal_Toxin_Microcystin" },
{ "sTitle": "Recreational_Guideline_20" },
{ "sTitle": "Blue_Green_Algae_Cells" },
{ "sTitle": "Recreational_Guideline" }
]
});
} else {
//algaeTable.fnDestroy();
$(".algae_table > tbody").empty();
algaeTable.fnDraw();
//$('.algae_table').find("tr:gt(0)").remove();
}
},
error: function () {
alert("Data is not available for this location at the present time, please check back at a later time. Thank you.");
}
});
}
I am trying to query 2 different Google Fusion tables and return each table under a new tab within a google infoWindow. However, I am running into issues because I can't seem to return an array or string from the $.ajax function to the parent scope. For example, the items array above returns undefined. Any thoughts around this is greatly appreciated.
Thanks in advance,
Michael
It is definitely possible. You haven't provided enough code to determine what's wrong, e.g. queryURL, queryText, etc. You'll need your Google API key as well. Here is an example demonstrating how to do it.
https://developers.google.com/fusiontables/docs/samples/basic_jsonp_request

jqGrid change dynamically edittype for specific row

Following to this post where I found some way to do that I would want to get, I meet some trouble with it.
Here is my code :
var myDlg = $("#dlgpers"),lastsel;
myDlg.jqGrid({
url:'pers.php?id='+dataRow.id,
mtype:'GET',
datatype: "json",
ajaxGridOptions: { cache: false },
height:250,
cmTemplate: {sortable:false},
gridview: true,
cellEdit:true,
scroll:false,
colNames:['Id','Label','Information','Type','Data'],
colModel:[
{name:'id',index:'id',hidden:true,key:true},
{name:'label',index:'label',align:'right',width:100,editable:false,
cellattr: function (rowId, val, rawObject, cm, rdata) {
return ' style="font-weight:bold;margin-right:5px;border-left:0;border-top:0;" class="ui-state-active"' ;
}
},
{name:'info',index:'info',width:200,editable:true,edittype:'text'},
{name:'type',index:'type',width:30,hidden:true},
{name:'data',index:'data',width:30,hidden:true}
],
loadComplete: function () {
var rowIds = myDlg.jqGrid('getDataIDs');
$.each(rowIds, function (i, row) {
var rowData = myDlg.jqGrid('getRowData',row);
if (rowData.type == 'select') {
myDlg.jqGrid('restoreRow', row);
var cm = myDlg.jqGrid('getColProp', 'info');
cm.edittype = 'select';
cm.editoptions = { value: rowData.data };
myDlg.jqGrid('editRow', row);
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
}else{
myDlg.jqGrid('restoreRow', row);
var cm = myDlg.jqGrid('getColProp', 'info');
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
myDlg.jqGrid('editRow', row);
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
}
});
}
});
and the result as image :
and the JSON response :
{"page":1,"total":1,"records":1,"rows":[
{"cell":[0,"Nom ","LEBRUN","text",""]},
{"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},
{"cell":[2,"Initiales ","LJ","text",""]},
{"cell":[3,"Fonction ","","text",""]},
{"cell"[4,"Service,"Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
{"cell":[5,"T\u00e9l\u00e9phone ","","text",""]},
{"cell":[6,"Email ","","text",""]},
{"cell":[7,"Statut ","CDI","select","0:CDI;1:CDD;2:App;3:Stg;4:Int"]},
{"cell":[8,"Entr\u00e9 le ","2008-10-06","text",""]},
{"cell":[9,"Sorti le ","0000-00-00","text",""]}]}
Two questions I submit to your knowledge:
As you can see, the second line (Prénom) don't seem editable, but it is.
I don't understand why these inputs are visible, as I would want they appear only if I edit some cell.
Many thanks for all your kind help for resolve (and explain) my wrong way.
JiheL
UPDATED 2013-03-29
I have applied your answer code and that run fine ! Many thanks.
But I have created another form in such a way for another subject, and that cause me some troubles.
Here is the code of this new form :
var showAbs=function(){
$('#EditDialog').empty();
var $table=$('<table></table>')
.attr('id','dlgcong')
.appendTo($('#EditDialog'));
var myCong = $("#dlgcong");
myCong.jqGrid({
url:'xpabs.php?id='+id+'&y='+y,
datatype: "json",
height:"auto",
cmTemplate: {sortable:false},
gridview: true,
colNames:['Type absence','Début','Fin','id'],
colModel:[
{name:'abs',index:'abs',width:155,editable:true,edittype:'select',
editoptions:{
dataUrl:"selabs.php",
dataEvents: [
{
type: 'change',
fn: function(e) {
$(this).parent().css('background-color','#'+$(this).find('option:selected').attr('colr'));
if($(this).find('option:selected').attr('colr')=='ffffff'){
$(this).parent().parent().find('input').datepicker('disable');
}else{
$(this).parent().parent().find('input').datepicker('enable');
$(this).parent().parent().attr('changed',true);
}
}
}
]
},
cellattr: function (rowId, val, rawObject, cm, rdata) {
return ' style="background-color:#'+rawObject[4]+';color:white;"';
}
},
{name:'debut',index:'debut',align:'center',width:70,editable:true},
{name:'fin',index:'fin',align:'center',width:70,editable:true},
{name:'id',index:'id',hidden:true}
],
jsonReader: {
cell: "",
root: function (obj) {
return obj;
}
},
loadComplete: function (data) {
var $self = $(this),
cm = $self.jqGrid("getColProp", "debut"),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item;
for (i = 0; i < l; i++) {
item = data[i];
cm.editoptions = {
dataInit: function(element) {
$(element).datepicker({
setDate:item[1],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
}
}
var cm = $self.jqGrid("getColProp", "fin");
for (i = 0; i < l; i++) {
item = data[i];
cm.editoptions = {
dataInit: function(element) {
$(element).datepicker({
setDate:item[2],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
}
$self.jqGrid("editRow", idPrefix + item[3]);
}
myCong.find('select').each(function(){
$(this).css({
backgroundColor:'transparent',
color:'white',
border:0,
width:155
});
});
},
idPrefix: "cong",
rowNum: 10000
});
//********************
// Button ' Valider '
//********************
$('<input />')
.attr({
type:'button',
})
.css({
float:'right',
marginTop:'5px'
})
.click(function(){
var toBeSaved='';
myCong.find('tr[changed=true]').each(function(idx){
if(toBeSaved.length>0){
toBeSaved+='|';
}
toBeSaved+=$(this).find('td:eq(3)').text()+';';
toBeSaved+=$(this).find('select option:selected').val()+';';
toBeSaved+=$(this).find('input:eq(0)').val()+';';
toBeSaved+=$(this).find('input:eq(1)').val();
});
if(toBeSaved.length>0){
$.ajax({
url:'majpabs.php?id='+id+'&data='+toBeSaved,
async:false,
dataType:'json',
success:function(data){
myGrid.trigger('reloadGrid');
$('#newAbs').val(' Nouveau ').attr('disabled',false);
}
});
}
})
.val(' Valider les absences ')
.appendTo($('#EditDialog'));
//*******************
// Button ' Retour '
//*******************
$('<input />')
.attr({
type:'button',
id:'newAbs'
})
.css({
float:'left',
marginTop:'5px'
})
.click(function(){
showPers();
})
.val(' Retour ')
.appendTo($('#EditDialog'));
//********************
// Button ' Nouveau '
//********************
$('<input />')
.attr({
type:'button',
disabled:false
})
.css({
float:'left',
marginTop:'5px',
marginLeft:'7px'
})
.click(function(){
if($(this).val()==' Nouveau '){
var myRow = {abs:"0", debut:'00/00/'+y, fin:'00/00/'+y, id:'0'};
myCong.jqGrid('addRowData','',myRow, 'last');
$(this).val(' Sauver ').attr('disabled',true);
}else{
}
})
.val(' Nouveau ')
.appendTo($('#EditDialog'));
}
and the result as image :
As you can see, the first row does not receive select and datepicker as other rows. Strange !
When I add new row, it does not receive select and datepicker as the first row.
I think I'm wrong in understanding this method.
I'm worry to bother you with these questions, I had a look in wiki without success to find any way to make these points correct. I would like to find some more detailed tutorial which show some cases examples.
Thank you VERY MUCH if you can spend again some time for give me a way to be more efficient with jqGrid.JiheL
UPDATED 2013-04-01
I have applied Oleg's suggestions and that works now. But a trouble remains.
here is the image :
For the first row, select box is OK.
The first input field receive datepicker, but the second (the column called 'fin') not !
All others rows receive well datepickers, but not the last field of first row.
Here is the code :
loadComplete: function (data) {
var $self = $(this),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item,
cm;
for (i = 0; i < l; i++) {
item = data[i];
cm = $self.jqGrid("getColProp", "debut");
cm.editoptions = {
dataInit: function(element) {
//alert('deb'+i);
$(element).datepicker({
setDate:item[1],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
};
$self.jqGrid("editRow", idPrefix + item[3]);
//
cm = $self.jqGrid("getColProp", "fin");
cm.editoptions = {
dataInit: function(element) {
//alert('fin'+i);
$(element).datepicker({
setDate:item[2],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
};
$self.jqGrid("editRow", idPrefix + item[3]);
}
myCong.find('select').each(function(){
$(this).css({
backgroundColor:'transparent',
color:'white',
border:0,
width:155
});
});
},
Another time, I hope you can help me to resolve this trouble and close this request.
Many thanks for all the time you spend to help newbies.
JiheL
I think that many from the problems in your code common. So I tried to answer on you question more detailed.
First of all you posted wrong JSON data. The line
{"cell"[4,"Service,"Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
contains two errors:
no ':' after "cell"
no " after "Service
After the changes the line will be so
{"cell":[4,"Service","Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
and JSON data could be read. The next problem is the usage of numbers together with string in one array. Because the bug in the line of jqGrid code
idr = ccur !== undefined ? ccur[idn] || idr : idr;
ids could not be integer value 0. I posted the bug report about the error. To fix the problem using existing code of jqGrid you should use strings instead of numbers. For example the line
{"cell":[0,"Nom ","LEBRUN","text",""]},
should be changed to
{"cell":["0","Nom ","LEBRUN","text",""]},
Without the changes you will have id duplicates. Both first lines ({"cell":[0,"Nom ","LEBRUN","text",""]} and {"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},) will get the same id equal to 1 instead of 0 and 1. It was the main reason of the problem which you described.
Additionally I would recommend you the following:
remove cellEdit:true option. You use editRow later in the code. It means that you use inline editing instead of cell editing which means cellEdit:true. You can't combine both editing modes in one grid.
replace height:250 option to height:"auto"
remove all index properties from colModel. Remove all properties of colModel with default values (edittype:'text', editable:false)
remove options of jqGrid with default values (mtype:'GET', scroll:false)
all parameters of functions in JavaScript are optional. So if you don't use for example any parameters of cellattr callback you can replace cellattr: function (rowId, val, rawObject, cm, rdata) {...} to cellattr: function () {...}
the callback loadComplete has one parameter data which can provide you all data which returned from the server. So you don't need to use getDataIDs and getRowData. The array data.rows can by directly used.
if you use data parameter of loadComplete callback you can remove unneeded 'type' and 'data' columns from the grid.
if you place information about id after 'Label','Information' then you can use id property of jsonReader and remove hidden id column from the grid too. For example if you move id as the last in the cell array you can use jsonReader: {id: 4} and remove hidden id column from the grid. If you add additionally cell: "" property in jsonReader you can remove "cell": from the input data. If you would use root property of jsonReader defined as function (see the documentation) you can remove some unneeded data from the server response.
For example the server can produce the simplified data
[
["Nom ","LEBRUN","text","","0"],
["Pr\u00e9nom ","Jacques","text","","1"],
["Initiales ","LJ","text","","2"],
["Fonction ","","text","","3"],
["Service","Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests","4"],
["T\u00e9l\u00e9phone ","","text","","5"],
["Email ","","text","","6"],
["Statut ","CDI","select","0:CDI;1:CDD;2:App;3:Stg;4:Int","7"],
["Entr\u00e9 le ","2008-10-06","text","","8"],
["Sorti le ","0000-00-00","text","","9"]
]
The corresponding jqGrid could be
$("#dlgpers").jqGrid({
url: "pers.php?id=" + dataRow.id,
datatype: "json",
height: "auto",
cmTemplate: {sortable: false},
gridview: true,
colNames: ["Label", "Information"],
colModel: [
{name: "label", align: "right", width: 100,
cellattr: function () {
return ' style="font-weight:bold;margin-right:5px;border-left:0;border-top:0;" class="ui-state-active"';
}},
{name: "info", width: 200, editable: true}
],
jsonReader: {id: 4, cell: "", root: function (obj) { return obj; } },
loadComplete: function (data) {
var $self = $(this),
cm = $self.jqGrid("getColProp", "info"),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item;
for (i = 0; i < l; i++) {
item = data[i];
cm.edittype = item[2] === "select" ? "select" : "text";
cm.editoptions = { value: item[3] };
$self.jqGrid("editRow", idPrefix + item[4]);
}
},
idPrefix: "dlg",
rowNum: 10000 // to have no paging
});
See the demo:

Resources