I have code like this:
$(document).ready(function () {
if ($('#au').length <= 0) {
return;
}
var $project = $('#au');
$project.autocomplete({
minLength: 4,
source: function (request, response) {
$.ajax({
dataType: "json",
type: 'post',
cache: false,
data: {term: request.term},
url: '/Movies/ajax/',
success: function (data) {
if (isNaN($('#au').val())) {
response($.map(data, function (item) {
return {
label: item.Movies__name + " " + "(" + item.Movies__id + ")",
value: item.Movies__name
}
}));
} else {
response($.map(data, function (item) {
return {
label: item.Movies__id + " " + "(" + item.Movies__name + ")",
value: item.Movies__id
}
}));
}
}
});
},
select: function(event, ui) {
$("#au").val(ui.item.value);
$("#au").submit();
},
create: function (event, ui) {
},
open: function (event, ui) {
}
});
});
This code works fine. Basicly when You type in form "Alie", you will get
Alien(22)
Aliens2(32)
Aliens3(43)
Or when you type Id istead of movie name, you will get:
(22)Alien
(22)Other and so on....
So this code returns list of data - movie and id.
And now i want, to have first result without id, so when You type movie name like "Alie" you will get:
Alien
Alien(22)
Aliens(32)
First match without id.
Thanks for any replies.
response($.map(data, function (item, i) {
return {
label: item.Movies__name + (i != 0 ? " (" + item.Movies__id + ")" : ""),
value: item.Movies__name
}
}));
Use i for index in map function. If 0, you don't show id.
Related
I am generating dynamic textboxes for autocomplete depending on user input.
var projects = [
{
label: "Test12",
desc: "responsive web application kit"
},
{
label: "Londinium",
desc: "responsive bootstrap 3 admin template"
},
{
label: "It's Brain",
desc: "Bootstrap based "
}
];
// Initialize autocomplete
$(document).on('click', '.ac-custom', function () {
$(this).autocomplete({
minLength: 0,
source: function (request, response)
{
$.ajax({
url: "/Home/GetInfo",
type: "POST",
dataType: "json",
data: { Name: $(this).val() },
success: function (data) {
}
});
},
focus: function (event, ui) {
$(this).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(this).val(ui.item.label);
return false;
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>").append("<span class='text-semibold'>" + item.label + '</span>' + "<br>" + '<span class="text-muted text-size-small">' + item.desc + '</span>').appendTo(ul);
}
});
If I give the source as projects this works but I need to fetch from database so I am calling an action method but somehow this is not working.
Is it because I am binding ajax call to controls created at runtime.
Your help is appreciated. Thanks
You need pass data in response from success callback
// Initialize autocomplete
$(document).on('click', '.ac-custom', function () {
$(this).autocomplete({
minLength: 0,
source: function (request, response)
{
$.ajax({
url: "/Home/GetInfo",
type: "POST",
dataType: "json",
data: { Name: $(this).val() },
success: function (data) {
response( data );
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect. Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.';
}
alert(msg + "<br/>responseText: " + jqXHR.responseText);
}
});
},
focus: function (event, ui) {
$(this).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(this).val(ui.item.label);
return false;
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>").append("<span class='text-semibold'>" + item.label + '</span>' + "<br>" + '<span class="text-muted text-size-small">' + item.desc + '</span>').appendTo(ul);
}
});
Update you source function like this
source: function (request, response) {
$.ajax({
url: '/Home/GetInfo',
data: { 'text': $.trim($('#yourtextboxid').val()) },
dataType: 'json',
type: 'post',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.name,
id: item.id
}
}));
}
})
}
This will help you
I am trying to set a fallback function dynamically from an ajax jsonp call, but it doesn't seem to work - I am actually not quite sure if it is even possible - at least I believe I am doing it wrong.
I have this
var GetFacebookData = function (data) {
var dates = [{ "date_from": data.date_from, "date_to": data.date_to }]
$.each(data.datatypes, function (i, index) {
this.fbcallback[data.datatypes[i]["id"]] = function () {
LoadFacebookData(dates, data.datatypes["id"]);
}
$.ajax({
url: 'http://localhost:59380/' + data.datatypes[i]["urlfile"] + '.php?jsonp=fbcallback' + data.datatypes[i]["id"],
method: 'GET',
dataType: 'jsonp',
jsonp: 'fbcallback',
data: { "lpage": _bankArea, "hashed_token": CryptoJS.MD5("454545").toString(), "date_from": data.date_from, "date_to": data.date_to },
});
});
}
And I am calling the function with this
GetFacebookData({ date_from: _datefrom, date_to: _dateto, datatypes: [{ id: "moedsparnord", urlfile: "index" }, { id: "studiepakken", urlfile: "fb_studiedata" }] });
I am just getting
Uncaught TypeError: Cannot set property 'moedsparnord' of undefined
The whole concept is that I will need to run GetFacebookData multiple times with difference data to be executed.
/*** LOAD FETCHED DATA AS JSON ***/
var LoadFacebookData = function (dates, id) {
_dateLoader.hide();
$('.date-box form').slideUp(750, 'easeOutBack');
var pages = [];
this.loadcallback = function (data) {
var len = data["campaignData"].length;
$.each(data["campaignData"], function (index, value) {
$('#' + id + '-' + value["campaign"]["campaignId"]).find(".facebook").text(AddDecimal(value["campaign"]["campaignReach"]));
$('#' + id + '-' + value["campaign"]["campaignId"]).find(".facebook").attr("data-spend", value["campaign"]["campaignSpend"]);
if (index != len) {
pages[index] = [value["campaign"]["campaignId"], value["campaign"]["campaignSpend"]];
}
});
var string = $('#' + id + ' .total-facebook').text().replace(/,/g, '');
$("#" + id + " .total-facebook").countTo({
from: parseFloat(string),
to: data["totalReach"],
decimals: 0,
formatter: function (value, options) {
return value.toFixed(options.decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ".");
},
});
MSNLeadData([{ date_from: dates[0]["date_from"], date_to: dates[0]["date_to"] }, pages]);
StudieLeadData([{ date_from: dates[0]["date_from"], date_to: dates[0]["date_to"], pages }]);
}
$.ajax({
url: 'http://localhost:59380/loaddata.php?jsonp=loadcallback',
method: 'GET',
dataType: 'jsonp',
jsonp: 'loadcallback',
data: { "lpage": _bankArea, "hashed_token": CryptoJS.MD5("454545").toString(), "datatype": id },
});
}
Functions fbcallback['...'] should be global.
Try to use this code inside the loop.
...
var callbackName = 'fbcallback-' + data.datatypes[i]["id"];
window[callbackName] = function () {
LoadFacebookData(dates, data.datatypes["id"]);
}
...
$.ajax({
url: 'http://localhost:59380/' + data.datatypes[i]["urlfile"] + '.php',
method: 'GET',
dataType: 'jsonp',
jsonp: callbackName,
data: { "lpage": _bankArea, "hashed_token": CryptoJS.MD5("454545").toString(), "date_from": data.date_from, "date_to": data.date_to },
});
And inside of LoadFacebookData callback method should also be global (window.loadcallback).
I am trying to use jquery UI autocomplete, but somehow the same won't show up despite having no javascript error.
here is my json data:
{"d":"[{\"label\":\"XYZ\",\"desc\":\"desc 1\",\"value\":\"XYZ\",\"ID\":595,\"icon\":\"UM-892983\"},{\"label\":\"ABC .\",\"desc\":\"desc 2\",\"value\":\"ABC .\",\"ID\":1681,\"icon\":\"UM-432944\"}]"}
Here is my JS Function for processing the autocomplete:
$().ready(function(){
$("#txtName").bind("keyup", function (e) {
// Ajax call returns the above json data
// On Ajax Success I call
onSucName(returnData.d);
});
});
function onSucName(result) {
var varArrAdms = $.parseJSON(result);
$("#txtName").autocomplete({
source : varArrAdms,
select : function (event, ui) {
setNameValue(ui.item.icon)
$("#txtNo").val(ui.item.icon)
$("#btnSearch").click();
},
open : function () {
$(this).addClass('loadingTxtBox');
},
close : function () {
$(this).removeClass('loadingTxtBox');
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.value + " <b> desc:" + item.desc + "</b> <i> No:" + item.icon + "</i></a>").appendTo(ul);
};
}
Where am I wrong?
Try this example
$('#txtName').autocomplete({
source: function (request, response) {
$.ajax({
url: 'url',
data: {}, //pass data here
dataType: 'json',
type: 'post',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.icon
}
}));
}
})
},
select: function (event, ui) {
var itemval = ui.item.label;
// here you can access selected result `itemval`
return false;
},
minLength: 1
});
Why are you binding the autocomplete on keyup.... Rather you should bind it once.
Also, before rebinding it you shoud destroy the existing instance.
I am passing complex JSON data to jQuery autocomplete plugin. And it is working fine so it shows the list of Products.
Now I want to get somehow Price that is already included into JSON data and when I select product from autocomlete list I would like to populate input tag with Price.
I really cannot get if it is possible to do. What I know that data is already in JSON but how to get it?
Any clue?
Here is JS for jQuery autocomplete plugin
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
}
});
});
}
To make clear item.LastPrice has Price data.
And HTML
#Html.AutocompleteFor(x => x.ProductUID, Url.Action("AutocompleteProducts", "Requisition"), true, "Start typing Product name...", Model.Product.Name)
In your ui.item object you should be able to find the the Price property in there and then set the value in the select function.
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
price: item.LastPrice // you might need to return the LastPrice here if it's not available in the ui object in the select function
};
}));
},
..
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name'),
unitPriceEl = $('#price');
$('#' + hiddenFieldName).val(ui.item.UID);
unitPriceEl.val(ui.item.LastPrice); //set the price here
}
Thanks to dcodesmith!!! I am gonna mark his solution like an answer but just in case I will share my final code that is working fine now.
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
lastPrice: item.LastPrice
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
var unitPriceEl = $('#UnitPrice');
unitPriceEl.val(ui.item.lastPrice);
console.log(ui.item.lastPrice);
}
});
});
}
I'm trying to have a "No Results" message appear in the dropdown menu if there are no results. So for instance, if I type in "ABCD" into the text field, and there is no entity that matches, the message "No Results." will be displayed.
After looking through stackoverflow for the various different ways of accomplishing this, and trying a few of them, I still can't get it to work.
How can I add a "No Results" message to the dropdown menu when no results are found?
jQuery:
$element.autocomplete({
source: function (request, response) {
$.ajax({
url: thUrl + thQS,
type: "get",
dataType: "json",
cache: false,
data: {
featureClass: "P",
style: "full",
maxRows: 12
},
success: function (data) {
response($.map(data, function (item) {
if (data.indexOf(item) === -1) {
return { label: "No Results." }
} else {
return {
label: item.Company + " (" + item.Symbol + ")",
value: item.Company
}
}
}));
}
});
},
minLength: that.options.minLength,
select: function (event, ui) {
reRenderGrid();
}
});
I have tried adding an if() statement with the following but that didn't work.
if (data.length === 0) {
// Do logic for empty result.
}
I am able to overwrite the first entry with the text "No Result" if I do the following...
if (data.indexOf(item) === 0) {
return {
label: "No Results."
}
...but if I set data.indexOf(item) === -1 nothing shows up.
I just recently tried the following, and when there is no data, it goes into the loop, however, "No Results" is not being displayed in the menu:
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Company + " (" + item.Symbol + ")",
value: item.Company
}
}));
if (data.length === 0) {
label: "No Results."
}
}
I have also attempted to use the below example from Andrew Whitaker with no luck:
ANDREW WHITACKER'S FIDDLE: http://jsfiddle.net/J5rVP/128/
SOURCE: http://blog.andrewawhitaker.com/2012/10/08/jqueryui-autocomplete-1-9/
if (!ui.content.length) {
var noResult = { value:"",label:"No results found" };
ui.content.push(noResult);
//$("#message").text("No results found");
}
Fiddle
http://jsfiddle.net/J5rVP/129/
Update
Put the code at the end of your auto-complete setup just after select: function (event, ui) {..}
..........
minLength: that.options.minLength,
select: function (event, ui) {
reRenderGrid();
}, //HERE - make sure to add the comma after your select
response: function(event, ui) {
if (!ui.content.length) {
var noResult = { value:"",label:"No results found" };
ui.content.push(noResult);
}
}
});
Modify the function like this to check for length of data.
success: function (data) {
if(!data.length){
var result = [
{
label: 'No matches found',
value: response.term
}
];
response(result);
}
else{
// normal response
response($.map(data, function (item) {
return {
label: item.CompanyName + " (" + item.SymbolName + ")",
value: item.CompanyName
}
}));
}
}
My answer is almost identical to #neelmeg and #Trever, but I have added an extra check, so user won't be able to select the "no result" message:
$(".my-textbox").autocomplete({
minLength: 2,
open: function () { $('.ui-autocomplete').css('z-index', 50); },
source: function (request, response) {
$.ajax({
url: "/some-url",
type: "POST",
dataType: "json",
data: { prefix: request.term, __RequestVerificationToken: token },
success: function (data) {
if (!data.length) {
var result = [{ label: "no results", value: response.term }];
response(result);
}
else {
response($.map(data, function (item) {
return { label: item.someLabel, value: item.someValue };
}))
}
}
})
},
select: function (event, ui) {
var label = ui.item.label;
if (label === "no results") {
// this prevents "no results" from being selected
event.preventDefault();
}
else {
/* do something with the selected result */
var url = "some-url"
window.location.href = url;
}
}
});
For me the reason, why this messages occured were:
MISSING CSS FILES O JQUERY UI
so adding:
<link rel="stylesheet" href="jqueryui/themes/flick/jquery-ui.css" type="text/css" media="screen" />
<link rel="stylesheet" href="jqueryui/themes/flick/jquery.ui.theme.css" type="text/css" media="screen" />
solved my problem