jquery dynamic autocomplete textbox url - javascript

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

Related

Update DropDownList with AJAX

after typing client name #NAME1 im trying to get this client subaccounts #SUB in list from other table in db, but my list is empty . What im doing wrong?
html
<script type="text/javascript">
var kunnr; var ROLA;
$(document).ready(function () {
$('#NAME1').autocomplete({
source: function (request, response) {
$.ajax({
url: "Form2",
method: 'POST',
data: {
term: $('#NAME1').val()
},
success: function (data) {
response(data);
}});},
select: function (event, ui) {
kunnr = ui.item.kunnr;
}});});
$('#NAME1').change; ({
source: function (request, response) {
$.ajax({
type: "GET",
url: "Form3",
method: 'POST',
data: {
term: $('#SUB').val(), kunnr: kunnr, ROLA:"Slave"
},
success: function (data) {
response(data);
}});}, });
controller
[HttpPost]
public JsonResult Form2(string term)
{
return Json(db.KLIENCI.Where(c => (term!=null && c.NAME1.Contains(term))||(term==null)).OrderBy(x=>x.NAME1).Take(10).Select(a => new { label = a.NAME1,kunnr=a.KUNNR }));
}
[HttpPost]
public JsonResult Form3(string term, string kunnr)
{
return Json(db.CLI2LOGIN.Where(c => ((term != null && c.LOGIN.Contains(term)) || (term == null))&& c.KUNNR== kunnr && c.ROLA == "Slave").OrderBy(x => x.LOGIN).Select(a => new { label = a.LOGIN }).ToList(),JsonRequestBehavior.AllowGet);}
Please find below an example:
View:
<script>
$(document).ready(function () {
$('.maincat').change(function () {
updateSubCategoryList($(this).val());
});
function updateSubCategoryList(catId) {
$('.subcat').empty();
$('.subsubcat').empty();
$.ajax({
url: '#Url.Action("GetSubCategories")',
type: 'Get',
data: { main: catId },
success: function (response) {
var subcat = $('.subcat');
subcat.append('<option value=""></option>');
if (response != null && response != '') {
$.each(response, function (index, value) {
subcat.append('<option value="' + this.SubCategoryID + '">' + this.SubCategoryDescription + '</option>');
});
}
}
});
}
</script>
Controller:
[HttpGet]
public JsonResult GetSubCategories(int main)
{
var i = _jobsservice.GetSubCategories(main);
return Json(i, JsonRequestBehavior.AllowGet);
}

Jquery autocomplete - how modify returned data

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.

Jquery UI auto complete (with custom listing) not working

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.

jQuery UI autocomplete- no results message

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

Ajax success function not waiting on internal script to complete before leaving scope

I have this chunk of code:
$.ajax({
type: "POST",
async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {
}
}]
});
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {}
}]
});
}
});
When the ajax return success it displays the dialog box for a whole 2 seconds or so (not long enough for a user to read the message that it contains) then closes it. Using chrome's debugger, I've determined that it runs out of scope without waiting for a confirmation on the dialog box inside the success function. Does anyone know how I would go about halting the code until the user clicks ok?
Here is the full chunk of code for that ajax call..
var leZDB = null;
function zipSelectedAttachments() {
var ids = getSelectedTaskIDs();
if (ids.length > 0) {
leZDB = $.Zebra_Dialog('Do you want to zip the attachment(s)?', {
'type': 'question',
'title': 'Confirmation',
'buttons': ['Yes', 'No'],
'onClose':function (caption) {
if(caption = 'Yes') {
LinkAndPass(ids);
}
}
});
} else {
$.Zebra_Dialog('No attachments are selected.', {
'type': 'error',
'title': 'Error',
'buttons': [
{ caption: 'Ok', callback: function () { } }
]
});
}
}
function LinkAndPass(ids) {
leZDB.close();
if (true)
{
SendIDSForZipping(ids);
}
}
function SendIDSForZipping(ids) {
var csList = '';
var userID = $('#hiduserID').val();
for (var i = 0; i < ids.length; ++i) {
csList += ids[i] + ',';
}
var $this = $(this);
$this.die('click');
$.ajax({
type: "POST",
//async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID+ "'}",
contentType: "application/json; charset=utf-8",
context:this,
dataType: "json",
success: function (data) {
var hasClickedOK = false;
var hasDisplayed = false;
if (!hasDisplayed) {
hasDisplayed = true;
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
hasClickedOK = true;
}
}
]
});
}
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
}
}
]
});
}
});
}
The getSelectedIDs() returns an array of numbers.
The Code behind returns a string.
try asyn:false in $.ajax({
type: "POST",
async: true
});
The problem consisted of the web method being called from the code behind. A faulty piece of logic caused it to refresh the page, instantly closing the box.

Categories