jQuery UI Autocomplete on KeyPress write value - jquery-ui

I am trying to implement jQuery UI Autocomplete the way like
when I have a list "alpha","beta","gamma" then type "a" into the input field
and only get "alpha" as proposal I want to hit enter and "alpha" shall be
the new value of the input field instead of selecting "alpha" by mouse click.
Is this possible?
$.ajax({
url : 'myAjax.php',
type : 'POST',
data : { param: getData },
dataType : 'json',
success : function(data) {
$("#myField").autocomplete({
minLength: 0,
source: data,
focus: function( event, ui ) {
$(this).val(ui.item.key);
return false;
},
select: function( event, ui ) {
$("#myField").val(ui.item.value);
return false;
}
});
}
});

you can add
autoFocus: true
this will make it focus on the first element that you get
and when you press enter it will automatically put the label in the field by using
$("#myField").val(ui.item.label);

Yes it's possible, you have to put more parameter on your autocomplete method
$( "#tags" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( data, function( item ){
return matcher.test( item.label );
}) );
},
minLength: 1,
select: function(event, ui) {
event.preventDefault();
$("#tags").val(ui.item.label);
$("#selected-tag").val(ui.item.label);
window.location.href = ui.item.value;
}
,
focus: function(event, ui) {
event.preventDefault();
$("#tags").val(ui.item.label);
}
});
see this exemple link

Related

triggering JQuery 'autocomplete' in a secondary textarea

We currently have two HTML textareas 'tinput'(primary) and 'toutput' (secondary) where we mimic the input in the primary to be reflected in the secondary as if someone is really typing in the secondary. The idea is to trigger an 'autocomplete' (over ajax) on the secondary. We have this working but not optimally.
We have attached a JQuery UI 'Autocomplete' (JQAC) to the secondary with a minLength:3 set. You may know that, normally, after 3 characters have been entered, JQAC 'buffers' the char entries thereon after and doesn't make an ajax call for every char that has been entered. Which is ideal.
However, with our secondary mimicking we have subverted this behavior, unfortunately, where after the 3rd char entry a JQAC ajax call is being made for every char after-- which is not optimal. We know why but don't know how to get around it. We believe we've subverted this because we are calling
$('#tinput').autocomplete('search',$('#tinput').val())
in the secondary's key handle, which by JQAC's documentation forces an ajax call.
To summarize, we need the secondary, that has JQAC attached to it, to behave as if someone were really typing into it and the JQAC behaving normally.
Here is JS for what we have as our char input mimic handling(we've changed variable names for this post so please ignore typos):
$("#tinput").on('input', function (e) {
$("#toutput").val($("#tinput").text());
var newEvent = jQuery.Event("keypress");
newEvent.which = e.which; // # Some key code value
$("#toutput").trigger(newEvent);
});
$("#toutput").keypress(function(e) {
$("#toutput").autocomplete('search',$("#toutput").val());
});
$( "#tinput" ).autocomplete({
appendTo: "#modalparent",
source: function( request, response ) {
$.ajax({
url: "https://xxxxxx",
type: "POST",
dataType: "json",
data: JSON.stringify({ "ourterm": request.term}),
success: function( data ) {
response( $.map( data.data.suggestions, function( item ) {
return {
label: item,
value: item
};
}));
}
});
},
minLength: 3,
select: function( event, ui ) {
// console.log( ui.item ?
// "Selected: " + ui.item.label :
// "Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
Any thoughts would be appreciated. Thanks!
We have found an elegant solution. It was a minor modification to our original.
change the trigger event by the primary to 'input' instead of the original 'keypress'.
remove the handler for the secondary.
here is the updated JS:
$("#tinput").on('input', function (e) {
$("#toutput").val($("#tinput").text());
var newEvent = jQuery.Event("input");
newEvent.which = e.which; // # Some key code value
$("#toutput").trigger(newEvent);
});
and delete:
//$("#toutput").keypress(function(e) {
// $("#toutput").autocomplete('search',$("#toutput").val());
// });
DONE.

jquery ui autocomplete with autoselect plugin

I am using a jquery ui autocomplete. when the user types in their own value, rather than selecting an item from the list, the textbox clears. This is ok (I don't want the user to be able to enter their own values) except if the user types in a value that does exist on the list.
I tried using the autoSelect plugin as detailed in this post, but it is not working - I added the plugin but when I type in a value that IS on the list and hit tab, I get the same results as before - the textbox clears.
Here is my autocomplete:
$(function () {
$('[id$="txtDocType').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/MyPage.aspx/myFunction",
data: "{'prefixText':'" + request.term.toLowerCase() + "', 'ddvId':'" + this.element.data('autocomplete') + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) { }
});
},
minlength: 1,
select: function (event, ui) {
$('#divOtherFields input[type=text], input[type=password]').prop("disabled", false).removeClass("disabled");
$('[id$="btnSaveNext"],[id$="btnSaveClose"]').prop("disabled", false);
$('[id$="txtReceiptDate"]').datepicker("setDate", new Date());
}
});
});
Here is the plugin:
(function( $ ) {
$.ui.autocomplete.prototype.options.autoSelect = true;
$( ".ui-autocomplete-input" ).on( "blur", function( event ) {
var autocomplete = $( this ).data( "autocomplete" );
if ( !autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" );
autocomplete.widget().children( ".ui-menu-item" ).each(function() {
var item = $( this ).data( "item.autocomplete" );
if ( matcher.test( item.label || item.value || item ) ) {
autocomplete.selectedItem = item;
return false;
}
});
if ( autocomplete.selectedItem ) {
autocomplete._trigger( "select", event, { item: autocomplete.selectedItem } );
}
});
}( jQuery ));
I set a breakpoint in the plugin on this line - "$( ".ui-autocomplete-input" ).on( "blur", function( event )" and the breakpoint was hit, yet the code would not step through. When I set a breakpoint to this line - "var autocomplete = $( this ).data( "autocomplete" );" the breakpoint was NOT hit.
Any ideas? I am at my wits end with this.
I solved this by making a couple of tweaks to the autoSelect plugin. Here is the code that eventually worked for me:
$(".ui-autocomplete-input").bind("focusout", function (event) {
var autocomplete = $(this).data("ui-autocomplete");
if (!autocomplete.options.autoSelect || autocomplete.selectedItem) { return; }
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i");
autocomplete.widget().children(".ui-menu-item").each(function () {
var item = $(this).data("ui-autocomplete-item");
if (matcher.test(item.label || item.value || item)) {
autocomplete.selectedItem = item;
return false;
}
});
if (autocomplete.selectedItem) {
autocomplete._trigger("select", event, { item: autocomplete.selectedItem });
}
});
I used the focus event to set the first value to a hidden variable. The same hidden variable also got updated in the select event. And then this was the hidden variable which I posted to the ajax call.
Why I did not use focus to set the value in the autocomplete input box, was because doing so populated the autocomplete input box even while I was typing in this box.
focus: function (event, ui) {
if($("#streetid")) $("#streetid").val(ui.item.label); //this was my hidden variable
}
},

autocomplete with amplifyjs

I'm trying to use jqueryui autocmplete with amplifyjs. Thats's to be able to switch between call to real server data and some hardcoded one and for additional flexibility.
For now I do not know how to make jqueryui autocomplete call amplify to refresh itself and perform search. I have the following codesnippet:
amplify.request.define('resId', 'ajax', {
url: 'autocmpleteUrl',
dataType: "json",
type: "POST"
});
$(elementId).autocomplete({
minLength: 1,
source: 'some url',
delay: 0,
focus: function (event, ui) {
$(elementId).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(elementId).val(ui.item.label);
return false;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
I know in autocomplete part it can both be url and json data. But I can't figure out how to make it deal with amplify and make it so that if user inputs text jquery autocomplete requests amplify, not the url itself. Any ideas?
That's close to what you want, but you've forgotten to pass the search term to your request. Your code should be:
$( elem ).autocomplete({
source: function( request, response ) {
amplify.request( "resId", request, function( data ) {
response( data );
});
});
});
Which will send the search term as the term query parameter. Since you're doing a direct passthrough of the data, this can also be reduced:
$( elem ).autocomplete({
source: function( request, response ) {
amplify.request( "resId", request, response );
});
});
However, in both of these cases you're not handling errors, which means that you can leave the autocomplete in the search state indefinitely. You should use the full amplify.request form to handle errors:
$( elem ).autocomplete({
source: function( request, response ) {
amplify.request({
resourceId: "resId",
data: request,
success: response,
error: function() {
response( [] );
}
});
});
});
I've completed with the following solution:
autocomplete({
source: function(request, response){
amplify.request('resId', function(data){
response(data);
});
},
So you can provide a function to jquery.ui autocomplete and in this function just set the request object and autocomplete data will be filled with data you provide.

jQuery UI Autocomplete how to implement Must Match in existing setup?

I have the following code and am curious as how to force the input to match the contents of the autocomplete:
$("#foo").autocomplete({
source: function( request, response ) {
$.ajax({
url: "index.pl",
dataType: "json",
data: {
type: 'foo',
term: request.term
},
success: function( data ) {
response( $.map( data.items, function( item ) {
return {
value: item.id
}
}));
}
});
},
minLength: 1
});
Answering this question for the benefit of anyone who stumbles upon this problem in 2013(yeah right!)
$("#my_input").autocomplete({
source: '/get_data/',
change: function(event, ui) {
var source = $(this).val();
var temp = $(".ui-autocomplete li").map(function () { return $(this).text()}).get();
var found = $.inArray(source, temp);
if(found < 0) {
$(this).val(''); //this clears out the field if non-existing value in <select><options> is typed.
}
}
});
Explanation:
The map() method creates a jQuery object populated with whatever is returned from the function (in this case, the text content of each <li> element).
The get() method (when passed no argument) converts that jQuery object into an actual Array.
Here is the original link of where I saw the solution.
I hope this helps. Thanks!

JQuery tiered Autocomplete that does not set data for the next tier

I have an Autocomplete for state and province names running. I want to pass the state abbreviation to the next cascade of Autocomplete. I created a hidden input and I want to set it to the abbreviation when the state name is selected, then I'll select the abbreviation for use in the next tier Autocomplete to limit the city query to one state only. At a prior step, I have country radio buttons setting a state limit in the .ajax data option, so you can see (generally) what I want to do in this state/city tier. I've tried several things, done a lot of Google searching and reading jQuery books, but I need some help. The stateProvince input box autocompletes and selects the full state name. The hidden input does not get set with the abbreviation. The alert is empty. I'm not sure about either the ajax success or the ajax select functions. How do I get the abbreviation (not the name) to be the value of the hidden input? and how can I then select it in the next tier's .ajax data option? Here is the relevant code.
selected HTML without tag symbols:
input type="text" id="stateProvince" name="stateProvince" size="50" maxlength="50"
input type="hidden" id="hiddenState" name="hiddenState"
Autocomplete source ajax;
$("#stateProvince").autocomplete
({
source: function( request, response )
{
//Pass the selected country to the php to limit the stateProvince selection to just that country
$.ajax(
{
url: "getStateProvince.php",
data: {
term: request.term,
country: $('input[name=country]:checked').val() //Pass the selected country to php
},
type: "POST",
dataType: "json",
success: function( data )
{
response( $.map( data, function( item )
{
return{
label: item.stateName,
value: item.name,
abbrev: item.stateAbbrev
}
}));
},
select: function( event,ui )
{
$(this).val(ui.item.value);
$("#hiddenState").$(this).val(ui.item.abbrev);
}
});
alert('|' + $("#hiddenState").val() + '|2nd'); //doesn't trigger here; shows no content when placed in the next tier Autocomplete
},
minLength: 2
});
JSON example returned from php:
[{"stateName":"Alabama","name":"Alabama","stateAbbrev":"AL"},{"stateName":"Alaska","name":"Alaska","stateAbbrev":"AK"}]
You've almost got it! I see the following problems:
select is an event on the autocomplete widget. Your code as it is right now is defining select as an option to the $.ajax({...}); call.
The alert statement that's failing is inside the source function to the autocomplete widget. I'm guessing it pops up right after you start typing. The reason it's empty is because it is not inside the select function (and it takes place before your AJAX call comes back successfully).
You can tweak your code as follows:
$("#stateProvince").autocomplete
({
source: function( request, response )
{
//Pass the selected country to the php to limit the stateProvince selection to just that country
$.ajax(
{
url: "getStateProvince.php",
data: {
term: request.term,
country: $('input[name=country]:checked').val() //Pass the selected country to php
},
type: "POST",
dataType: "json",
success: function( data )
{
response( $.map( data, function( item )
{
return{
label: item.stateName,
value: item.name,
abbrev: item.stateAbbrev
}
}));
}
});
},
select: function( event,ui )
{
$(this).val(ui.item.value);
$("#hiddenState").val(ui.item.abbrev);
alert('|' + $("#hiddenState").val() + '|2nd'); //doesn't trigger here; shows no content when placed in the next tier Autocomplete
},
minLength: 2
});
Note the location of the alert statement and the select event handler.
Here is the code for both the 2d state tier and 3d city tier of the Autocomplete.
//2d tier - stateProvince: autocomplete selection
//set the country for the 2nd tier to select stateProvince from only the country selected in the 1st tier
$("#stateProvince").autocomplete
({
source: function( request, response )
{
//Pass the selected country to the php query manager to limit the stateProvince selection to just that country
$.ajax(
{
url: "getStateProvince.php",
data: {
term: request.term,
country: $('input[name=country]:checked').val() //Pass the selected country to php
},
type: "POST", // a jQuery ajax POST transmits in querystring format in utf-8
dataType: "json", //return data in json format
success: function( data )
{
response( $.map( data, function( item )
{
return{
label: item.stateName,
value: item.name,
abbrev: item.stateAbbrev
}
}));
}
});
},
select: function( event,ui )
{
$(this).val(ui.item.value);
$("#hiddenState").val($(this).val(ui.item.abbrev));
//alert('|' + $("#hiddenState").val() + '|1st'); //shows [object,Object]
},
minLength: 2
});
//3d tier - city: autocomplete selection //
$( "#city" ).autocomplete
({
source: function( request, response )
{
$.ajax(
{
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data:
{
featureClass: "P",
country: $('input[name=country]:checked').val(),
adminCode1: $("#hiddenState").val(), //"AK", //works-delivers only Alaska towns.
style: "full",
maxRows: 10,
name_startsWith: request.term
},
success: function( data )
{
response( $.map( data.geonames, function( item )
{
return{
label: item.name + (item.adminName2 ? ", " + item.adminName2 : "") + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name + (item.adminName2 ? ", " + item.adminName2 : "") + (item.adminName1 ? ", " + item.adminName1 : "")
}
}));
}
});
},
select: function( event, ui )
{
$(this).val(ui.item.value);
//ui.item.option.selected = true;
//self._trigger( "selected", event, {item: ui.item.option});
}, //combo box demo uses this to bar illegal input. Other things are needed also. item.option is not defined
minLength: 2,
open: function()
{
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function()
{
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});

Resources