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.
Related
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!
I have a Kendo Grid and I want to pass a parameter to my Controller Action. I am able to use the transports read.data successfully but I'm trying to learn how to use the parameterMap functionality.
Here is what I have that works:
<script>
$(document).ready(function () {
var employeeNumber = #(ViewBag.EmployeeNumber); //passed in from controller
$("#ShoppingCartGrid").kendoGrid({
dataSource: {
dataType: "json",
type:"GET",
transport: {
read: {
url:"../Requisitions/GetShoppingCartSummary/",
data: {
employeeNumber:employeeNumber //passing param this way works
},
}
},
schema: {
...... //omitted for brevity
</script>
Here is what does not work but I don't know what I should put here:
<script>
$(document).ready(function () {
var employeeNumber = #(ViewBag.EmployeeNumber);
$("#ShoppingCartGrid").kendoGrid({
dataSource: {
dataType: "json",
type:"GET",
transport: {
read: {
url:"../Requisitions/GetShoppingCartSummary/"
},
parameterMap:function(options,operation){ // here is where I'm
if (operation == "read") { // running into issues- even
return employeeNumber:"140412"; // hard coding param- no joy
}
};
},
schema: {
...... //omitted for brevity
</script>
I have looked for hours for a solution but I can't seem to find a post that explains this concept well enough for me to grasp. Please don't send links to Kendo's documentation, been there, have the mental scars to prove it. Thanks for any suggestions.
Your transport datatype is Json, therefore you need to return valid Json parameters. Kendo appends result of function provided in parameterMap to the method name you defined in your url.
In your case - employeeNumber:"140412" is not a valid Json, you need to provide parmas in following format { paramname : value , otherparamname : value }.
It is very handy to use JSON.stringify(o) to get your params correct.
Below structure for parameterMap works for me:
parameterMap: function (o, operation) {
var output = null;
switch (operation) {
case "create":
output = '{ id: ' + JSON.stringify(o) + ' }';
break;
case "read":
output = '{ id: ' + globalVariable + ' , filters: ' + JSON.stringify(o) + '}';
break;
case "update":
output = '{ id:' + JSON.stringify(o) + '}';
break;
case "destroy":
output = '{ id : ' + o.param+ ' }';
break;
}
return output;
}
Bit more detail as per your comment :
parameterMap: function (o, operation) {
var output = null;
switch (operation) {
case "read":
var txt1 = $('#myTextBox1').val();
var txt2 = $('#myTextBox2').val();
var txt3 = $('#myTextBox3').val();
output = '{ textBoxValue1: ' + txt1 + ', textBoxValue2: ' + txt2 + ',textBoxValue3: ' + txt3 + '}';
break;
}
return output;
}
Server side method signature should look like :
GetShoppingCartSummary(string textBoxValue1, string textBoxValue2, textBoxValue3);
OK, I figured it out. I had to enclose the return statement in curly brackets.
Here is what I ended up with that works:
<script>
$(document).ready(function () {
var employeeNumber = #(ViewBag.EmployeeNumber);
$("#ShoppingCartGrid").kendoGrid({
dataSource: {
dataType: "json",
type:"GET",
transport: {
read: {
url:"../Requisitions/GetShoppingCartSummary/"
},
parameterMap:function(options,operation){
if (operation == "read") {
return{
employeeNumber:employeeNumber
};
};
} //parameterMap
}, //transport
schema: {
....Omitted for Brevity
</script>
I would still like to figure out some other options like how to build an array of optional parameters and then return the array. But this is the answer to the question I asked. Hope it helps someone else.
I am new to JqGrid. I have a problem with reload JqGrid. Not getting any errors also.
jQuery("#gridData").jqGrid("setGridParam",
{ type: "POST",
url: "TablesCoolView.aspx/GetTableData",
data: "{TableName :'" + "Test" + "'}",
contentType: "application/json",
dataType: "json"
}).trigger("reloadGrid", [{ current: true }]);
The Code will go here,
onPaging: function (pgButton) {
//debugger;
var pagerId = this.p.pager.substr(1); // get paper id like "pager"
var currentPage = jQuery("#gridData").jqGrid("getGridParam", 'page'); //get current page
var lastPage = jQuery("#gridData").jqGrid("getGridParam", 'lastpage'); //get last page
if (currentPage - 1 == lastPage - 1)
jQuery("#gridData").jqGrid("setGridParam", { page: lastPage }).trigger("reloadGrid"); // set the requested page to the last page value – then reload
var currentRecordCount = jQuery("#gridData").jqGrid("getGridParam", 'reccount'); //get the record count
var recordsPerPage = jQuery("#gridData").jqGrid("getGridParam", 'rowNum'); // get the records per page
var newValue = 0; // new value
if (pgButton === "user") {
newValue = $(".ui-pg-input").val();
}
else {
if (pgButton.indexOf("next") >= 0)
newValue = ++currentPage;
else if (pgButton.indexOf("prev") >= 0)
newValue = --currentPage;
else if (pgButton.indexOf("last") >= 0)
newValue = jQuery("#gridId").jqGrid("getGridParam", 'lastpage');
else if (pgButton.indexOf("first") >= 0)
newValue = 1;
}
alert(pgButton);
//alert(newValue);
jQuery("#gridData").jqGrid("setGridParam", { page: newValue }).trigger("reloadGrid"); // set the requested page to the last page value – then reload
currentRecordCount = jQuery("#gridData").jqGrid("getGridParam", 'reccount'); // read the current page records
//alert('RecordCount: ' + currentRecordCount + ' RecordsPerPage: ' + recordsPerPage);
if (currentRecordCount < recordsPerPage) {
startRange = 1;
endRange += endRange;
alert("Grid Reload test Start");
//jQuery("#gridData").jqGrid("setGridParam", { type: "POST", url: "TablesCoolView.aspx/GetTableData", page: 1, async: true, loadOnce: true, data: "{TableName :'" + "Test" + "'}", contentType: "application/json", dataType: "json" }).trigger("reloadGrid");
jQuery("#gridData").jqGrid("setGridParam", { type: "POST", url: "TablesCoolView.aspx/GetTableData", data: "{TableName :'" + "Test" + "'}", contentType: "application/json", dataType: "json" }).trigger("reloadGrid", [{ current: true }]);
alert("Grid Reload test End");
//jQuery("#gridData").jqGrid("setGridParam", { datatype: "json", data: "{TableName :'" + tableName + "', \"PageSize\" :\"" + recordsPerPage + "\", \"PageNumber\" :\"" + newValue + "\"}", url: "TablesCoolView.aspx/GetNextSetOfRecords" }).trigger("reloadGrid");
//data: "{TableName :'" + tableName + "', \"PageSize\" :\"" + recordsPerPage + "\", \"PageNumber\" :\"" + newValue + "\"}",
}
}
Dont know where am doing wrong.
Please help me out of this.
Try changing data: "{TableName :'" + "Test" + "'}", to postData: "{TableName :'" + "Test" + "'}",
I was working with MVC CheckBox for.
#Html.CheckBoxFor(m=>m.IsActive, new { #id = "IsActive",#checked = "checked" })
if ($('#frmmenu').valid())
{
//alert("MenuTitle=" + $("#MenuTitle").val() + "&OrderNumber=" + $("#OrderNumber").val() + "&IsActive=" + $("#IsActive").val());
alert("MenuTitle=" + $("#MenuTitle").val() + "&OrderNumber=" + $("#OrderNumber").val() + "&IsActive=" + $("#IsActive").val());
$.ajax({
type: 'POST',
url: '/api/MenuWebApi/SetMenu',
data: "MenuTitle=" + $("#MenuTitle").val() + "&OrderNumber=" + $("#OrderNumber").val() + "&IsActive=" + $("#IsActive").val(),
success: function (data)
{
if (data.Success == true)
{
//window.location = '/Profile/UserProfile';
}
},
error: function (xhr, textStatus, errorThrown)
{
//window.location = JsErrorAction;
},
dataType: "json",
headers:
{
'RequestVerificationToken': JsTokenHeaderValue
}
});
}
return false;
with passing data when checkbox is checked it is giving true value, but if unchecked then it will give true value not false, how could i do?
please help me anyone.
Regards
Try with this:
var isActive = ($('#IsActive').attr('checked') == 'checked');
// $('#IsActive').attr('checked') will return
// 'checked' or undefined - if not checked/not containing 'checked' attribute
I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};