I am using jquery-ui-1.11.4 and autocomplete. My source is obtained by ajax which is properly returning this type of JSON
[
{"label":"foo", "value":"01-1013"},
{"label":"bar", "value":"01-1003"}
]
When I scroll down to select my choice everything works correctly. The value is added to printTag and the label is added to the text box (inputTag). The problem is that as I use the down arrow to select my choice, the value is displayed in the text box, not the label. The label is ONLY displayed in after I select my choice.
I read a couple of reviews and have tried to modify my code but I can't figure it out. Here is my autocomplete.
$(inputTag).autocomplete({
source: function(request, response) {
$.ajax({
url: myAjaxFile,
method: "GET",
dataType: "JSON",
data: getData+'='+ request.term,
success: function(data){
response(data)
}
});
},
focus: function(event, ui){
event.preventDefault();
$(inputTag).val(ui.item.label);
return false;
},
select: function(event, ui) {
$(printTag).val(ui.item.value);
// prevent autocomplete from updating the textbox
event.preventDefault();
$(inputTag).val(ui.item.label);
return false;
},
minLength: 2
});
How do I display the label in the text box rather than the value?
Related
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.
I've following jquery ui autocomplete, that grabs data from google places...
Problem I'm having is that, once user starts going through the list of suggests via up and down arrows, original input also appears at the end. I want to remove this original input, otherwise if user hits enter form saves without forcing selection...
// Autocomplete location with google places API
$("#edit_profile .location").autocomplete({
source: function(request, response) {
$.ajax({
url: "/words/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("");
}
}
});
I'm not sure if i get the question the right way, but if i did, try "focus" method instead of the "change" method.
So the code would look like this:
// Autocomplete location with google places API
$("#edit_profile .location").autocomplete({
source: function(request, response) {
$.ajax({
url: "/words/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,
focus: function (event, ui) {
if (!ui.item){
$(this).val("");
}
}
});
You can not catch this with change event course it happen before, so I tried to change it to focus event but this event only fired when you select smth from suggestion list.Also I think default behavior have logic because in case I didn't found what I want in list I would like to have option to came back and continue typing.
But anyway if you want to change this behavior you can prevent from user access to input field after the ajax return.
For example with position the suggest box over input field.
<ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all" role="listbox" aria-activedescendant="ui-active-menuitem" style="z-index: 1; top: 0px; left: 0px; display: block; width: 298px;">
Here is the demo.
Is your concern about disabling the default action when hitting [Enter] while the autocomplete menu is visible ?
If so, here is a solution : add some flag to your input, and if that flag is set, prevent the default action on keydown :
var $input = $('input[name="name"]');
$input.on('keydown', function(e) {
if ( $(this).data('acShown') && e.which == 13 /*enter key*/){
e.preventDefault();
}
});
$input.autocomplete({
source: function (request, response) {
setTimeout(function () {
$input.data('acShown', true); //set the flag when showing the menu
response(data)
}, 300);
},
close: function(){
$input.data('acShown', false); //unset the flag on close
}
});
fiddle
In the fiddle : as you can see, when the menu is shown, hitting [Enter] when the focus is on the input won't trigger the form submission - you will stay on the current page.
I have a jQuery autocomplete field which gets results from Amazon's autocomplete, as you can see in the source below. There's a function that I need to call every time the user hovers his cursor over an item on the autocomplete list.
The functions itself isn't the problem, it's that I don't know how to call it. So for simplicity, let's say that I just need to alert the item that the cursor is over. If I wanted to do that onClick, I suppose I could add a select property but how do I do it onMouseOver?
Here's the jQuery:
$(document).ready(function () {
//http://completion.amazon.com/search/complete?method=completion&q=halo&search-alias=videogames&mkt=1&x=updateISSCompletion&noCacheIE=1295031912518
var filter = $("#new_item").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://completion.amazon.com/search/complete",
type: "GET",
cache: false,
dataType: "jsonp",
success: function (data) {
response(data[1]);
},
data: {
q: request.term,
"search-alias": "stripbooks",
mkt: "1",
callback: '?'
}
});
}
});
});
the autocomplete list is in the dom as an ul with the class="ui-autocomplete ..." The menu-items are inside that as li's with class="ui-menu-item" So tying onMouseover to them with jQuery:
$('.ui-autocomplete .ui-menu-item').hover(mouseInHandler, mouseOutHandler); More info on the hover function can be found here.
If i got it right, you want to select an entry in your autocomplete list when mouseover event is triggered? Then you can do:
$j('.ui-autocomplete').on('mouseover', '.ui-menu-item', function () {
$(this).find('a').click();
});
Just write:
$('#element').hover(function()
{
alert('hoho!');
});
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}
}))
}
});
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?