jQuery UI Autocomplete - javascript

I am using jQuery UI's autocomplete plugin and everything is well and good except for that fact that when a user clicks the value they want the function I have assigned to the "select:" method fires before the value of the field is changed. So if I type "Foo" in the input field, then click the autocomplete match for "Foo Bar" the function detects the value as what was typed (in this case "Foo") as opposed to the value which was selected from the autocomplete list. Once the function fires (in this case I just have an alert box popup with this.value) the value of the input field is set to the value selected via the autocomplete list. This problem does not occur if the user selects the option with the keyboard (arrow keys->tab), only when the mouse is used.
$(function()
{
var aEmps =
[
<?php
echo $sEmps;
?>
];
$("#slast").bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active )
{ event.preventDefault(); }
})
.autocomplete({
source: aEmps,
select: function(event, ui)
{
var aName = $(this).val();
alert(aName);
}
})
});
Since most users will be interacting with this using their mouse I have to find a way to get the value set before firing the "select:" function. I believe I can accomodate for this by adding a condition to the statement prior to the auto complete but I need some help finding the right syntax.

Looking at the documentation, it looks like the select event is fired as the selection is being updated, not after the selection is updated. Try using the change event instead of select, and see if that solves your problem.

After trying a number of approaches I found that by simply binding the callback function to the close event works very well. I added some error handling to catch values that aren't selected from the list and I am off and running!
Here is the updated code:
$(function()
{
var aEmps =
[
<?php
echo $sEmps;
?>
];
$("#slast").bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active )
{ event.preventDefault();}
})
.autocomplete({
source: aEmps,
close: function(event, ui)
{
alert(this.value);
}
})
});

Related

How to detect manual entry or selection in Jquery AutoComplete

I have this jsfiddle for Jquery autocomplete
https://jsfiddle.net/fp7n8em5/
I want to identify , if the text inside the autocomplete field was a manual entry or a selected one from dropdown
when i was debugging this , i found out that the eventype is same for both that is autocompletechange
basically i need to clear some of the fields if its a manual entry and don't want to do it when its a selection
my code
$( "#tags" ).autocomplete({
source: availableTags,
select : selectedOne,
change: changedOne
});
function selectedOne()
{
alert('belongs to selectedOne')
}
function changedOne()
{
alert('belongs to changedOne')
}
});
Can you differentiate the data coming from the external source?
For example you can return an extra parmeter (ie: ID), or you can add a fixed parameter (ie: type = external).
Then, when change fires, you test the returned object, if there is the parameter, then it comes from dropdown.
Or you can set input hidden variable and then you'll test if this variable is empty.
Here is an example:
$( "#tags" ).autocomplete({
source: availableTags,
minLength: 2,
select: function( event, ui ) {
document.formname.input_type_hidden.value = ui.item.id;
}
});
<form name="formname"><input type="hidden" name="input_type_hidden" value=""></form>

jquery autocomplete How to set label and how to get value?

I have a dynamic input field created with class name as sub-category.
On key press autocomplete is working fine, from which i can select one.
Working code for that is below
$("body").on('keypress', 'input.sub-category', function () {
var availableTags = [
{label:"ActionScript", value:"1"},
{label:"ActionScript1", value:"11"},
{label:"ActionScript2", value:"12"},
{label:"ActionScript3", value:"13"},
{label:"ActionScript4", value:"14"},
];
$(this).autocomplete({
source: availableTags,
});
});
When i select one of the autosuggested text say 'ActionScript', it's value (1) should be available in the below code, how i can access it? On select alert function is working fine, so just need to know how to access value of the selected label.
$("body").on('autocompleteselect', 'input.sub-category', function () {
alert('here');
});
In addition to that i would like to know how to set the selected text in the input box rather than it's value.
you need to include jquery-ui file
"https://code.jquery.com/ui/1.12.0/jquery-ui.js" in your file
and
just replace
$("body").on('autocompleteselect', 'input.sub-category', function () {
alert('here');
});
with the following lines.
$("body").on('autocompleteselect', 'input.sub-category', function (event,ui) {
alert(ui.item.label);
alert(ui.item.value);
});
and
$(this).autocomplete({
source: availableTags,
});
with
$(this).autocomplete({
source: availableTags,
select:function(event,ui){
$(".sub-category").val(ui.item.label);return false;
}
});
and this will work fine for more info please go on following link
http://api.jqueryui.com/autocomplete/
More than easy!
It's here http://api.jqueryui.com/autocomplete/#event-select
And it says, that You may bind handler in such manner
$( ".selector" ).on( "autocompleteselect", function( event, ui ) {} );
where ui is Object which has item which in turn has selected label and value data.

How to send a variable via jquery

I just created an autocomplete textbox via jquery now i am stuck with two problems.
1) I need to get the value of the selected item from the Autocomplete list.
So far i did these..
My jquery
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
I am getting the autocomplete list from the database its working fine, but the problem is that
2) When i type 'r' all the names with values gets populated and if i select say Robin from the list and try to display it with alert, i only gets 'r', (i only typed r,and selected 'robin' from list) why is this so?
here is the code i wrote for this
for the autocomplete textbox
<input name="tags" type="text" id="tag" value="" onchange= "newfn()" />
and in newfn()
<script>
function newfn()
{
authname = document.getElementById("tag").value;
document.autoquote.qid.value=authname;
alert(authname);
}
</script>
and if i put an alert at first saying
alert("Hi");
then, i get first alert saying hi, and I get robin not r
So what is the correct way to get what value i selected from the autocomplete list?
Now my second Question is that the selected value from this autocomplete textbox, I need to pass it with another jquery to another php page so that I can get this value there and give it in a query as a criteria.
Because it is not the way to catch a select event http://api.jqueryui.com/autocomplete/#event-select :
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true,
select: function( event, ui ) {
//Then use "ui" object, for example ui.item.label or ui.item.value
}
});
});
$(".autosearch-smart").autocomplete('autocomplete.php', {
select: function( event, ui ) {
// here you can get id and values from the autocomplete list
// try to debug
console.log(ui.item.id);
console.log(ui.item.label);
console.log(ui.item.value);
}
});
you can use the autocomplete's select property like this
$("#tag").autocomplete('autocomplete.php', {
selectFirst: true,
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
alert(label);
alert(value)
// you can write additional javascript code here to make use of these values
}
});
Please check the jQuery UI documentation for more examples and info.
Here is a JSFiddle.(Please note that an additional source attribute has been added in the fiddle to simulate the loading of data set as real cross domain AJAX calls are not allowed)
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
select: function( event, ui ) {
//check the values in console
alert(ui.item.value+" - "+ui.item.value);
}
});
});

Customised jQuery autocomplete

I have a customised jQuery autocomplete control that is declared something like this.
$('#SystemCode_Autocomplete').autocomplete({
source: [{"label":"Access","value":0},{"label":"Documentum","value":0}], //move values
minLength: 1,
change: function(event, ui) {// some function},
select: function(event, ui) {// some function}
});
The change and select events are custom.
The problem is if I type something into the textbox then click the submit button (i.e. no tab out, or lost of focus), or if I press the key to submit after typing into the text box, the change event isn't fired and it has to be before I submit.
I was hoping to do it without putting javascript behind the submit button, and to ideally do it from within the autocomplete control itself. I tried adding the change to the blur event.
${'foo').blur(function() { $('bar').trigger('autocompletechange');
// or
${'foo').blur(function() { $('bar').change();
But none of them have worked, anyone have any ideas?
You can try something like this:
$('#SystemCode_Autocomplete').autocomplete({
source: [{"label":"Access","value":0},{"label":"Documentum","value":0}], //move values
minLength: 1,
change: function(event, ui) {/* some function */},
select: function(event, ui) {/* some function */}
}).each(function(){
var self = $(this).closest("form").submit(function(e){
self.trigger("change");
// you may not need anything like this...but whatever
if(!functionToCheckIfFormIsValid()){
e.preventDefault();
}
});
});
focus function autocomplete
Before focus is moved to an item (not selecting), ui.item refers to the focused item. The default action of focus is to replace the text field's value with the value of the focused item, though only if the focus event was triggered by a keyboard interaction. Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused.
Solve the problem:
$('#SystemCode_Autocomplete').autocomplete({
source: [{"label":"Access","value":0},{"label":"Documentum","value":0}], //move values
minLength: 1,
focus: function( event, ui ) {
return false;
},
select: function(event, ui) {
alert('Select Event:'+ui.item.value);
}
});
So your problem is that you have to make sure that action a occurs before action b and you're having trouble reconciling that between two event handlers? That actually sounds like a pretty common UI problem, not something that's limited to jQuery.
How would you solve it in any other circumstance? What if I suggested you to use the jQuery data object to attach to the element and then do some sort of semaphore checking in each method, like setting a flag in the one method, and in the other method checking to see if the flag is set?
That's how I would do it, were it me.
DEMO: http://ask.altervista.org/demo/jquery-autocomplete-help/
$(function() {
var json = [{"label":"Access","value":0},{"label":"Documentum","value":0}];
$('#SystemCode_Autocomplete').autocomplete({
source: function( request, responce ) {
responce( $.map( json, function( item ) {
return { id: item.value, label: item.label, value: item.label }
}));
$.each( json, function( i, item ) {
if ( request.term.toLowerCase() == item.label.toLowerCase() ) {
// do something here, ex.: AJAX call or form submit...
$('#submit_button').click();
}
});
},
minLength: 1,
change: function(event, ui) { /*alert(ui.item.label + ' ' + ui.item.id)*/ },
select: function(event, ui) {}
});
});
Ok I completely for to update this to what we actually did to get it to work.
Basically we editted the autocomplete .js file to get it to do want we wanted.
Specifically we added our own options to the autocomplete then we editted the _response method to something like this
_response: function (content) {
if (content.length) {
content = this._normalize(content);
this._suggest(content);
this._trigger("open");
this.options.isInError = false;
this.element.removeClass("input-validation-error");
} else {
this.close();
if (this.element.val() == '') {
this.options.hiddenField.val('');
} else {
this.options.hiddenField.val('-1');
}
if (this.options.mustBeInList) {
this.options.isInError = true;
this.element.addClass('input-validation-error');
}
}
this.element.removeClass("ui-autocomplete-loading");
},
That way we know if the User is entering "rubbish" as they type and the controll goes red and into an "error"mode. To stop them from posting back we do this
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open or has focus
if (self.options.isInError == true) {
return false;
}
if (self.menu.element.is(":visible")) {
event.preventDefault();
}
//passthrough - ENTER and TAB both select the current element
case keyCode.TAB:
if (!self.menu.active) {
return;
}
self.menu.select(event);
break;

jQuery UI Autocomplete behaviour. How to search free text on enter?

first question (and hopefully, but doubtfully my only one)
I'm using the jQuery UI Autocomplete. Here is sample code to replicate my issue.
var suggestions = ["C", "Clojure", "JavaScript", "Perl", "PHP"];
$("#autocomplete").autocomplete({
source: suggestions
});
When a user types 'J' they will be presented with 'Clojure' and 'JavaScript' as suggestions.
I have omitted Java from this list, if the user wants to search for Java, they type 'Java', press the enter key but the form does not submit. If you add a space the 'JavaScript' suggestion disappears and the form can be submitted by pressing the enter key.
I am creating a free search, I want users to be able to search by pressing enter even if there are suggestions available.
$("#autocomplete").keypress(function(event) {
alert(event.keyCode);
if (event.keyCode=='13') $this.closest('form').submit();
});
I tried the above thinking I could manually detect a submit keypress and submit the form, but the alert shows all keys are detected EXCEPT submit which seems to be suppressed by the autocomplete.
Any help is greatly appreciated! Thanks.
UPDATE
I had to make a few changes, but this code works fine on my side after doing that. First, e.keycode should be e.keyCode. I didn't think the case mattered, but it does. Also, make sure you are not quoting the 13 when you check for the keyCode to be the enter button. It will not work correctly if you do so. Here's the new code:
var suggestions = ["C", "Clojure", "JavaScript", "Perl", "PHP"];
$("#autocomplete").autocomplete({
source: suggestions
}).keypress(function(e) {
if (e.keyCode === 13) {
$(this).closest('form').trigger('submit');
}
});
The keypress function should look like below, and also, you can chain the autocomplete and keypress functions to make it easier on you. Below code should work.
var suggestions = ["C", "Clojure", "JavaScript", "Perl", "PHP"];
$("#autocomplete").autocomplete({
source: suggestions
}).keypress(function(e) {
if (e.keycode === 13) {
$(this).closest('form').trigger('submit');
}
});
I had a similar problem, the jquery-ui autocomplete widget fires the select event when the user selects a suggestion from the list, whether the selected suggestion was clicked or the enter key was pressed. But it did nothing if the user typed text and pressed the enter key without selecting an item from the list. When that happens, I need to do a search.
It was easy to add a keypress event handler, but it fired whether a selection had been made or not. So I added a variable, didSelect, to maintain the selection state.
Here's the complete solution:
$(function() {
var didSelect = false;
$( "#search" ).autocomplete({
source: "/my_remote_search",
minLength: 2,
search: function (event, ui) {
didSelect = false;
return true;
},
select: function( event, ui ) {
if (ui.item) {
didSelect = true;
my_select_function(ui.item);
}
}
}).keypress(function(e) {
if (e.keyCode == 13) {
if ( ! didSelect ) {
my_search_function( $("#search").val() );
}
}
});
});
Using the UI Autocomplete plugin version 1.8.5:
Look for this bit of code
"case d.ENTER:case d.NUMPAD_ENTER:a.menu.element.is(":visible")&&c.preventDefault();"
and remove or comment it out.
Essentially what was said above but from the current version of the plugin.
cheers
Pete
This is what I did
<div class="ui-widget">
<form action="javascript:alert('hey run some javascript code')">
<input id="search" />
</form>
</div>
Autocomplete supresses submit but this worked as a workaround for me:
jQuery.fn.go_url = function(id) {
var url="gl10.pl?ar=2010&listi=ts&niv=stovnsnr&rl=1290693052914&stovnsnr=replaceme";
var ok;
if (ok=id.match(/^\d{6}$/)) {
url=url.replace(/replaceme/g,id);
location=url;
}
}
jQuery(function() {
jQuery( "#stovnar" ).autocomplete({
source: "autocomplete.pl?pname=stovnsnr",
minLength: 3,
select: function( event, ui ) { if (ui.item) { jQuery.fn.go_url(ui.item.id); } }
});
}).keypress(function(e) {
if (e.keyCode === 13) {
v=jQuery("#stovnar").val();
jQuery.fn.go_url(v)
}
});
I had the same problem, and was thinking of using validation to accomplish this, but in the end my solution looks a whole lot easier than other solutions on this page:
Make an input field to type the text in, named #input and a hidden input named #hiddeninput. Your search-backend will have to use the value for #hiddeninput.
Inside your autocomplete, set the value of #hiddeninput to request.term: (I set this inside $.ajax({ success: }) )
$("input#hiddeninput").val(request.term);
Set the autocomplete with the select:-method to fill the hidden input with the suggestion that is chosen:
select: function( event, ui ) {
$("input#input").val(ui.item.label),
$("input#hiddeninput").val(ui.item.nr),
//Auto-submit upon selection
$(this).closest("form").submit();
}
Now your search will be performed on what the user has typed until he selects something from the suggestions-list.
<script>
$(function() {
$('#student').autocomplete({
source: '../ajx/student_list.php',
minLength: 3,
response: function( event, ui ) {
$('#student_id').val(ui.content[0].id);
},
select: function( event, ui ) {
$('#student_id').val(ui.item.id);
$(this).closest('form').trigger('submit');
}
}).keypress(function(e) {
if (e.keyCode === 13) {
$(this).closest('form').trigger('submit');
}
});
});
</script>
<div>
<form action='../app/student_view.php'>
<input name='student_id' id='student_id' type='hidden' value=''>
<label for='student'>Student: </label>
<input id='student' />
</form>
</div>
Here I used autocomplete to search for a student. If the user pressed ENTER, the form would submit, even if nothing was selected from the list. The 'response' event would update the value of a hidden input field with the first item in the list. They could also click or select from the list.

Categories

Resources