JQuery AutoComplete not displaying - javascript

I have used JQuery UI autocomplete to cut down on the list of parts I have to display in a drop down, I am also using json to pass the list of parts back but I am failing to see the results, I am sure this is to do with my limited understanding of JQuery's Map function.
I have the following json
{"parts":[{"partNumber":"654356"},{"partNumber":"654348"},{"partNumber":"654355-6"},{"partNumber":"654355"},{"partNumber":"654357"},{"partNumber":"654357-6"},{"partNumber":"654348-6"}]}
which on JSONLint is validated correct
I have viewed the post and response utilising Firebug and seen them to be correct but my auto complete does not seem to display, the closest I have got it to doing so, was when I displayed the entire JSON string with each character having a new line.
here is my JS
$('.partsTextBox').autocomplete({
minLength: 3,
source: function(request, response) {
$.ajax({
url: './PartSearch.ashx',
data: $('.partsTextBox').serialize(),
datatype: 'JSON',
type: 'POST',
success: function(data) {
response($.map(data, function(item) {
return { label: item.partNumber }
}))
}
});
},
select: function(e) {
ptb.value = e;
}
});
Any help anyone can give would be much appreciated. Have edited to include help given by soderslatt

I'm not sure, but shouldn't parts.part be an array ?
http://jsfiddle.net/jfTVL/3/

From the jQuery autocomplete page:
The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.
Which means that if you use "value" instead of "partNumber", you should get want you want.

jquery autocomplete plugin format out have to
{"query":"your_query","suggestions":["suggestions_1","suggestions_2"],"data":[your_data]}}
and use autocomplete that
$('#your_input').autocomplete({
minChars: 2
, serviceUrl: './PartSearch.ashx'
, deferRequestBy: 50
, noCache: true
, params: { }
, onSelect: function(value, data) {
}
, ajaxCallBack: function() {
response($.map(data, function(item) {
return { label: item.partNumber}
}))
}
});

Related

JQuery autocomplete - Unable to set the source dynamically

I am trying to do the following. I have a date picker. When I select a date (during data change event), I am doing a ajax call to get data that I need to populate in a autocomplete drop down. When the page loads for the first time, the autocomplete box will be empty. As and when the date is changed or selected, the autocomplete box should populate accordingly. Please check my code below.
When I initiate the dataSrc variable, the drop down loads for the first time without any issues.
The issue that I am having is with the dynamic population, the data that I am fetching from the ajax call is not being set in the autocomplete source dynamically.
Please advice.
var dataSrc = [];
$(document).ready(function() {
$("#dropdownselector").autocomplete({
source : dataSrc,
change : function(event, ui) {
$("#selector").val(0);
$("#selector").val(ui.item.id);
}
}).focus(function() {
$(this).autocomplete("search", " ");
});
$('#dateselector').on("changeDate", function() {
$.ajax({
type : "GET",
url : "../getDropDownData",
data : {
"dateSelected" : $('#dataSelected').val()
},
contentType : "application/x-www-form-urlencoded; charset=utf-8",
dataType : "json",
async : true,
cache : false,
success : function(data) {
dataSrc = JSON.stringify(data);
},
error : function(data) {
alert('There was an error while fetching data.')
}
})
});
});
dataSrc = JSON.stringify(data); replaces what dataSrc points to. It does not change the original array element that was given to the autocomplete.
You could try pushing all the elements from the data into the dataSrc, which would cause the array that dataSrc originally pointed to, to not change, but get new values.
Or if that does not work, you may have to use the https://api.jqueryui.com/autocomplete/#method-option method to change the source option for the autocomplete.
$("#dropdownselector").autocomplete( "option", "source", data);
Inner your success function you need to destroy the old autocomplete and redraw it. Maybe, you need to create a function to create the autocomplete ('drawAutocomplete').
...
success : function(data)
{
dataSrc = JSON.stringify(data);
$( "#dropdownselector" ).autocomplete( "destroy" );
drawAutocomplete();
},
...

Always show autocomplete list, even if search doesn't match

I have an autocomplete field, and on type I go to the PHP/Database to retrieve the matching options.
Thing is, my suggestion list isn't exactly matches of the text. I explain:
Say I type "Jon". My list will bring from the database "John Doe", "Jonatan", etc. Only "Jonatan" will be visible as the suggestion to the input, but I do need them all, because it considers approximation (there's a soundex element on my backend search).
My JavaScript/Ajax code:
function prePatientsList(){
//I'm limiting search so it only starts on the second character
if (document.getElementById("name").value.length >= 2) {
try
{
listExecute.abort();
}catch(err) {
null;
}
var nome= $("#name").val();
var nomeList = "";
listExecute = $.ajax({
url: '/web/aconselhamento/Atendimento/PrePacientesAutocomplete',
type: "POST",
async: true,
datatype: 'json',
data: { nome: nome}
}).done(function(data){
source = JSON.parse(data);
});
$(function() {
$("input#nome").autocomplete({
source: source,
// I know I probably don't need this, but I have a similar component which has an URL as value, so when I select an option, it redirects me, and I'll apply you kind answer on both.
select: function( event, ui ) {
ui.item.label;
}
});
});
}
}
Thanks.
I think you'd have to set your remote endpoint directly as the autocomplete's source (e.g. similar to https://jqueryui.com/autocomplete/#remote) so that it's the backend which does all the filtering. Right now, the autocomplete effectively thinks you've fed it a static list of options from which further filtering should take place, and therefore it decides to handle the filtering itself.
Your code can be as simple as this I think, no need to have a separate handler or an ajax request outside the scope of the autocomplete.
$(function() {
$("input#nome").autocomplete({
minLength: 2, //limit to only firing when 2 characters or more are typed
source: function(request, response)
{
$.ajax({
url: '/web/aconselhamento/Atendimento/PrePacientesAutocomplete',
type: "POST",
dataType: 'json',
data: { nome: request.term } //request.term represents the value typed by the user, as detected by the autocomplete plugin
}).done(function(data){
response(data); //return the data to the autocomplete as the final list of suggestions
});
},
// I know I probably don't need this, but I have a similar component which has an URL as value, so when I select an option, it redirects me, and I'll apply you kind answer on both.
select: function( event, ui ) {
ui.item.label;
}
});
});
See http://api.jqueryui.com/autocomplete/#option-source for more info.

JQuery UI AutoComplete: .data(...) is undefined [but only when I am add a second autocomplete box]

I am using JQuery 1.8.3 and JQuery UI 1.8.24.
This is the code, that works just fine:
$(function () {
$("#").autocomplete({
source: function (request, response) {
$.ajax({
url: '', type: "POST", dataType: "json",
data: { searchPattern: request.term },
cache: false,
success: function (data) {
response($.map(data, function (item) {
return { label: item.Label, value: item.Value, id: item.Id, description: item.Description }
}))
}
});
},
delay: 300,
minLength: 2,
autoFocus: true
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("li>/li>")
.data("ui-autocomplete-item", item)
.append("a>" + item.label + "br>div style=\"font-size:x-small;font-style:italic;\">" + item.description + "/div>/a>")
.appendTo(ul);
};
});
But if I add a second textbox to the HTML, copy the JavaScript above and change the selector and url (so in the end I have two autocomplete textboxes), then I get the following error for the second autocomplete:
TypeError: $(...).autocomplete(...).data(...) is undefined
With one autocomplete it works perfect, but with a second not
I can't explain why. Does anyone can help me?
Thanks in advance!
Toby
EDIT:
I found the problem.
The JavaScript code is in an *.js file and the two textboxes are in two different *.thml files.
So there is only one textbox at a time and this is the problem.
Now I do the last part (with the data(...)) in the *.html file and it works fine:
$("#selector").autocomplete().data("autocomplete")._renderItem = renderItem;
Thank for your help!
There was a change in the data key naming convention in UI 1.9
jQuery 1.9/1.10 removed the key autocomplete and added uiAutocomplete
.data("uiAutocomplete")
Please note: according to latest Documentation (v1.10.x) it should be .data("ui-autocomplete")
(see: http://jqueryui.com/autocomplete/#custom-data)
The other day, I encountered the same issue, but it had nothing to do with the version I was using but simply that the element being aucomplete-ed did not exist! Try
alert($('...').length);
and make sure it is not zero.
You can implement the below mentioned line
.autocomplete( "instance" )._renderItem = function( ul, item ) {
instate of
.data("autocomplete")._renderItem = function (ul, item) {
as per the documentation available at Jquery site JQuery AutoComplete Funtionality you will find this code.
from upgraded version of jquery 1.10 they have made change in code.
hope this will help you.

Getting the Index of the selected item in jquery auto complete

I am using jQuery autocomplete, as follows:
From my PHP file, I am get json encoded arrays - one for ids and one for names.
I fill the autocomplete with names. In the select function, I am able to correctly alert
the selected item, but I am not able to get the index of the selected item. How do I get it?
$(function() {
$.ajax({
type: "POST",
url: "get_data.php",
success: function(data) {
data_array = jQuery.parseJSON(data);
$("#my_autocomplete").autocomplete({
source: data_array.names,
select: function(event, ui) {
alert(ui.item);
}
});
}
});
});
Example: http://jsfiddle.net/hY5Wt/
Instead of two arrays, you could have one array of objects. Each object would have a label and index: {label:"First", idx:1}. The autocomplete will use the label to display and on select event, you can access ui.item.idx to get the identifier/index.
$( ".selector" ).autocomplete({
source: [{label:"First", idx:1},
{label:"Second", idx:2},
{label:"Third", idx:3}],
select: function(event, ui) { alert(ui.item.idx); }
});
You link to an autocomplete plugin, but your code looks like you are using jQuery UI.

problem with jquery ui`s autocomplete select callback (1.8)

With this code:
function setupRow(event, ui) {
var textbox, // how do i get to the textbox that triggered this? from there
// on i can find these neighbours:
hiddenField = textbox.next(),
select = textbox.parents('tr').find('select');
textbox.val(ui.item.Name);
hiddenField.val(ui.item.Id);
$.each(ui.item.Uoms, function(i, item){
select.append($('<option>' + item + '</option>'));
});
return false;
}
function setupAutoComplete(){
var serviceUrl = "/inventory/items/suggest";
$("input.inputInvItemName").autocomplete({
source: function(request, response) {
$.ajax({
url: serviceUrl,
data: request,
dataType: "json",
success: function(data) {
response($.map(data.InventoryItems, function(item) {
return {
value: item.Name
};
}));
},
select: function(event, ui) {
setupRow(event, ui);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 3,
delay: 500
});
}
everything seems ok. Problem is the select handler never fires, not even the anonymous function that wraps my original delegate setupRow for debugging purposes is ever called.
anyone can see my error?
I also left a question in the comment: how do I get to the textbox that had the autosuggestion. Cannot use id here, because these text boxes are multiples and generated on the fly, interactively. Or is there another way to do the same thing?
Thanks for any help!
OP point of view
var textbox, // how do i get to the textbox that triggered this? from there
// on i can find these neighbours:
My Point of view
have you tried,
var textbox = $(event.target);
or you can do this,
OP point of view
select: function(event, ui) {
setupRow(event, ui);
},
My point of view
select: setupRow;
then
var textbox = this; // just a guess... wait..
anyone can see my error?
I think you forgot to put ';' .
$.ajax({
url: serviceUrl,
data: request,
dataType: "json",
success: function(data) {
response($.map(data.InventoryItems, function(item) {
return {
value: item.Name
}
}));
Or is there another way to do the same thing?
I think u are using the jquery ui autocomplete plugin.If yes, you can retreive like this.
$('.ui-autocomplete-input')
Otherwise, you can set a specific class to those textboxes and access those textbox through that class.
ok, got a step closer by using
inputs.bind("autocompleteselect", setupRow);
now setupRow fires.
Now it seems, that the success callback transforms the data, I get returned.I need to find a way, to both display the right value in the dropdown, without destroying the requests response...
Any ideas?

Categories

Resources