jQuery autocomplete with multiple items not working - javascript

I am working on jQuery autocomplete which as two items in a <ul>.
I am getting json item from $.getJSON function and the json object looks like :
[{
"merchant_name": "Myntra",
"merchant_details": "Flat Rs.225 Cashback"
}, {
"merchant_name": "Adlabs imagica",
"merchant_details": "Rs 170 per sale"
}, {
"merchant_name": "godaam",
"merchant_details": "Rs 140 per sale"
}, {
"merchant_name": "Homeshop18",
"merchant_details": "Upto 8% Cashback"
}]
My function looks as follows:
$('#search_bar').keyup(function(e) {
var searched = $('#search_bar').val()
$.getJSON('<?php echo base_url();?>get_data', 'title=' + searched, function(result) {
var elements = [];
$.each(result, function(i, val) {
elements.push({
'merchant_name': val.merchant_name,
'merchant_details': val.merchant_details
})
}) $('#search_bar').autocomplete({
delay: 0,
source: elements,
select: function(event, ui) {
$("input#search_bar").val(ui.item.merchant_name + " / " + ui.item.merchant_details);
$("#get").click();
}.data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a><strong>" + item.merchant_name + "</strong> / " + item.merchant_details + "</a>").appendTo(ul);
};
})
})
});
I am not able to proceed forward.
Please help me to solve this one.

I wrote this for one of my projects and it works perfectly. I'm not sure why you are detecting keyup when autocomplete does that for you... But this snippet should give you all the functionality you need.
$("#edit_profile .location").autocomplete({
source: function(request, response) {
$.ajax({
url: BASE_URL + "lib/ajax.php",
type: "GET",
data: "autocomplete_location=1&term=" + request.term,
cache: false,
success: function(resp) {
try {
json = $.parseJSON(resp);
} catch (error) {
json = null;
}
//
if (json && json.status == "OK") {
//
response($.map(json.predictions, function(item) {
return {
label: item.description,
value: item.description
}
}));
//
}
}
});
},
minLength: 1,
change: function (event, ui) {
if (!ui.item){
$(this).val("");
}
}
});

Related

Bootstrap Select2 doesn't firing select event on paste until type any word

I use bootstrap select2 v4.* on my site (Yii 2.x) and have met a problem:
The event select2:select doesn't firing on text paste with ctrl+v until I type any text. After typing - it works fine. What i'm doing wrong?
JS:
function formatResult(data) {
var content = '<span>' + data.id + '\t' + data.text + '</span>';
return $(content);
};
function formatSelection(data) {
var content = '<span>' + data.id + '</span>';
return $(content);
}
$('#wiz-asin-search').select2({
tags: true,
minimumInputLength: 3,
placeholder: 'specify asin..',
ajax: {
url: '/keyword-tracker/get-mwslisting-asins',
method: 'GET',
dataType: 'json',
data: function (params) {
return {
searchAsin: params.term
}
},
results: function (data) {
return { results: data.results };
}
},
templateResult: formatResult,
templateSelection: formatSelection,
escapeMarkup: function(m) { return m; }
}).on('select2:select', function(){
var asin = $(this).val();
console.log('asinSearch.change fired: ' + asin);
validationHighLight(false);
validateAsin(asin);
});
The solution is:
initialize select2 with some data.
$('#wiz-asin-search').select2({
// allowClear: true,
tags: true,
minimumInputLength: 3,
data: [
{
id: ' ',
text: 'testAsin'
}
],
...
and it will work fine.
You simply use this code:
$('#yourElement').select2();
Had a similar issue and resolved it using the createTag callback.
$('select').select2({
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
if (this.$element.find('option').length === 0) {
this.$element.append($('<option data-select2-tag="true">'));
}
return {
id: term,
text: term
}
}
});

jquery ui autocomplete custom data (item undefined )

My Script
$("#NameSearch").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
url: "/home/universalsearch/" + document.getElementById("filterUniversalSearchList").value + "/" + $("#NameSearch").val(),
type: "POST",
dataType: "json",
data: {
searchFilter: document.getElementById("filterUniversalSearchList").value,
term: request.term,
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.EmployeeName, id: item.EmployeeID}
}))
}
});
},
focus: function (event, ui) {
$("#NameSearch").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#NameSearch").val(ui.item.label);
return false;
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>")
.append("<div>" + item.label + "<br>" + item.id + "</div>")
.appendTo(ul);
};
});
Controller:
public JsonResult UniversalSearch(string searchFilter, string searchText)
{
var Employees = _home.GetEmployeeDetails(searchFilter, searchText);
return Json(new { data = Employees }, JsonRequestBehavior.AllowGet);
}
Problem I'm facing is in autocomplete dropdown I'm getting as undefined.
From controller it return as object array
I think I made mistake in binding data improperly.
dropdown result shows as undefined.
Is this problem due to jqueru-ui versions ?

Want to prevent selecting specific item in jQuery UI AutoComplete

I am developing textbox with autocomplete using jQuery UI Autocomplete.
After that, I can create textbox with autocomplete, but one issuce has occured now.
In my textbox, I want to prevent selecting specific item from autocomplete list.
If I select specific item, Autocomplete list display again or not to close.
$(function (prefixText) {
$("textBox").autocomplete({
autoFocus: false,
minLength: 0,
delay: 50,
source: function (request, response) {
var data = "{ 'prefixText': '" + prefixText
+ "','count': '" + 30
+ "','pixWidth': '" + 100 + "' }";
$.ajax({
type: "POST",
url: "Example.asmx/" + method,
cache: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
id: item.id,
name: item.name
}
}))
}
});
},
select: function (event, ui) {
var id = ui.item.id
//not match guid type
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
if ($("text_id") !== null) {
$("text_id").val(-1);
}
return false
}
else {
if ($("text_id") !== null) {
$("text_id").val(ui.item.id);
}
$("textBox").val(ui.item.name);
}
}
});
});
});
If someone know answer, please teach me.
Based on the example from here: How to disable element in jQuery autocomplete list
I think this code will work for you:
$(function (prefixText) {
$("textBox").autocomplete({
autoFocus: false,
minLength: 0,
delay: 50,
source: function (request, response) {
var data = "{ 'prefixText': '" + prefixText
+ "','count': '" + 30
+ "','pixWidth': '" + 100 + "' }";
$.ajax({
type: "POST",
url: "Example.asmx/" + method,
cache: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
id: item.id,
name: item.name
}
}))
}
});
},
select: function (event, ui) {
var id = ui.item.id
//not match guid type
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
if ($("text_id") !== null) {
$("text_id").val(-1);
}
return false
}
else {
if ($("text_id") !== null) {
$("text_id").val(ui.item.id);
}
$("textBox").val(ui.item.name);
}
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
//Add the .ui-state-disabled class and don't wrap in <a> if value is empty
var id = item.id
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul);
} else{
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
};
});
If you can provide a working version of your code (the items can also be from a predefined list, not based on ajax call) it will be much easier to help.

Cannot get selected item in jquery autocomplete

Using Jquery autocomplete UI widget, I have the following code that gets a list of suburbs/postcodes via external php:
<script>
$(function() {
$("#suburb").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'resources/php/helpers.php', //your server side script
dataType: 'json',
data: {
suburb: request.term
},
success: function (data) {
//if multiple results are returned
if(data.localities.locality instanceof Array)
response ($.map(data.localities.locality, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
//if a single result is returned
else
response ($.map(data.localities, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
},
select: function (event, ui) {
alert("SELECT");
$('#postCode').val("POSTCODE");
return true;
}
});
}
});
});
</script>
The autocomplete itself works well, I get the list of matches , however the 'select' part does not work, ie, I need to set another input text value to the value selected, but even in the above code, the Alert dialog does not get called - the various syntax I've seen has kind of confused me, so I'm not sure what I've done wrong here.
The selectfunction should be outside of the object that is sent to the ajax method.
Try this:
$(function() {
$("#suburb").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'resources/php/helpers.php', //your server side script
dataType: 'json',
data: {
suburb: request.term
},
success: function (data) {
//if multiple results are returned
if(data.localities.locality instanceof Array)
response ($.map(data.localities.locality, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
//if a single result is returned
else
response ($.map(data.localities, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
}
});
},
select: function (event, ui) {
alert("SELECT");
$('#postCode').val("POSTCODE");
return true;
}
});
});

JQuery Autocomplete select undefined error

I've been ripping my hair out for a few hours now and can't seem to find out why i've got an error.
When i call the following code :
$(document).ready(function () {
$("#searchBox").autocomplete({
select: function (event, ui) {
$("#searchBox").attr("readonly", true);
//this is where if i call alert(ui.long) I get undefiend
$("#CoorLong").val(ui.long);
$("CoorLat").val(ui.lat);
print_r(ui);
},
source: function (request, response) {
$.ajax({
url: "http://dev.virtualearth.net/REST/v1/Locations",
dataType: "jsonp",
data: {
key: "bingKey",
q: request.term
},
jsonp: "jsonp",
success: function (data) {
var result = data.resourceSets[0];
if (result) {
if (result.estimatedTotal > 0) {
response($.map(result.resources, function (item) {
return {
data: item,
label: item.name + '[' + item.point.coordinates[0] + ' ' + item.point.coordinates[1] + ']' + ' (' + item.address.countryRegion + ')',
value: item.name,
long: item.point.coordinates[0],
lat: item.point.coordinates[1]
}
}));
}
}
}
});
},
minLength: 1
});
});
As I said in the selec: function(event, ui) when i call ui.item or ui.value or ui.long I always get undefined
I implemented a print_r() to check the content and I do get this :
[item] =>object[data] =>object[__type] =>Location:http://schemas.microsoft.com/search/local/ws/rest/v1[bbox] =>object[0] =>48.83231728242932[1] =>2.2598159619433122[2] =>48.840042717570675[3] =>2.275464038056688[name] =>Quai d'Issy-les-Moulineaux, 75015 Paris[point] =>object[type] =>Point[coordinates] =>object[0] =>48.83618[1] =>2.26764[address] =>object[addressLine] =>Quai d'Issy-les-Moulineaux[adminDistrict] =>IdF[adminDistrict2] =>Paris[countryRegion] =>France[formattedAddress] =>Quai d'Issy-les-Moulineaux, 75015 Paris[locality] =>Paris[postalCode] =>75015[confidence] =>Medium[entityType] =>RoadBlock[label] =>Quai d'Issy-les-Moulineaux, 75015 Paris[48.83618 2.26764] (France)[value] =>Quai d'Issy-les-Moulineaux, 75015 Paris[long] =>48.83618[lat] =>2.26764
So i don't understand why it's undefined.
Thank you :)
From the documentation:
ui.item refers to the selected item.
So I think you want ui.item.long instead of ui.long.

Categories

Resources