10

I want to have auto complete functionality, where the text-box should get populated with the value list as a first item when there is an blur event.

I would like to have the functionality same as implemented in this link link

enter image description here

I have the code below, which populates on tab and enter key, but dont know how to achieve same functionality on blur event.

$( "#statelist" ).autocomplete({
    autoFocus: true,
    source: states,
    select: function (event, ui) {
        stateid = (ui.item.lable);
        $("#stateid").val(stateid);
    }
});

EDIT :- user enters a text lets us say type "che" and without pressing tab or enter key, user moves his control to next textbox, in this scenario I want the first list item to populated automatically in the textbox.

Thaillie
  • 1,362
  • 3
  • 17
  • 31
pappu_kutty
  • 2,378
  • 8
  • 49
  • 93

9 Answers9

11

You can send a enter key on blur event.

     $( "#statelist" ).blur(function(){
         var keyEvent = $.Event("keydown");
         keyEvent.keyCode = $.ui.keyCode.ENTER;
         $(this).trigger(keyEvent);
     }).autocomplete({
         autoFocus: true,
         source: states,
         // ...
     });

Here is the fiddle: http://jsfiddle.net/trSdL/4/

And here is a similar question. https://stackoverflow.com/a/15466735/1670643

Community
  • 1
  • 1
andyf
  • 3,262
  • 3
  • 23
  • 37
  • This answer does not working mate, plus it is causing so many alerts hanging up the page :S – Aditya Apr 06 '14 at 09:40
  • @pappu_kutty Sorry, I posted the wrong fiddle link. See my updated answer. – andyf Apr 09 '14 at 01:49
  • @Aditya Is `plus it is causing so many alerts hanging up the page` meaning the `event propagation`? If so , you can stop this event propagation. See http://jsfiddle.net/trSdL/5/ – andyf Apr 09 '14 at 02:29
  • @andyf this is working as i expected, but one issue i found, let us say i entered "a" and items listed in dropdown i hover over list itmes and moved away from the list, in this case none of the items selected and autocomplete doesnt work :) – pappu_kutty Apr 09 '14 at 02:38
  • @andyf How are you fetching the selected data object? – Aditya Apr 09 '14 at 05:32
  • @pappu_kutty Yes i found this issue too. I think it is a common problem for jQueryUI. And I think jQueryUI should provide a option for keeping stay on the first selection just like http://www.redbus.in/, or keeping stay on other selection when mouse over. I will try to find out the solution for this issue. Please let me know if you find the answer too. Thanks. – andyf Apr 09 '14 at 07:50
  • @andyf you are correct, it seems to be an issue with jquery ui as discussed here https://forum.jquery.com/topic/jquery-ui-hover-problem-autocomplete-combobox. – pappu_kutty Apr 09 '14 at 08:22
  • @pappu_kutty Also a discussion on SO http://stackoverflow.com/questions/11586399/jquery-autocomplete-loses-selection-on-mouse-out . But NO solution now :( – andyf Apr 09 '14 at 11:23
5

This is the Working DEMO

Use autoFocus: true option available for the autocomplete, and then put the first result obtained into your input box on the blur event,simple.

JS :

$("#tags").autocomplete({
    source: availableTags,
    autoFocus: true,
    selectFirst: true,
    open: function(event, ui) { if(select) select=false; },
    select: function(event, ui) { select=true; }
}).blur(function(){
    if(!select)
    {
        $("#tags").val($('ul.ui-autocomplete li:first a').text());
    }
});

If you have two autocomplete : Fiddle

If you have an associative array data: Eg:

var availableTags = [
    {'label': 'dog', 'value':1},
    { 'label' : 'cat' , 'value':2} ,
    {'label': 'ant', 'value':3},
    {'label': 'bat', 'value':4},
    {'label': 'deer', 'value':5},
    {'label': 'elephant', 'value':6},
    {'label': 'frog', 'value':7},
    {'label': 'giraffe', 'value':8},
    {'label': 'snake', 'value':9}
 ];

Use:

ui.item.label gives the label , ui.item.value gives the corresponding value : DEMO

select: function(event, ui) {
        $('#tags').val(ui.item.label); //shows label in autocomplete
        select=true;
        return false;
    }

You can also access data.autocomplete.selectedItem in your change event of autocomplete to get the selected autocomplete object ,See here

 change:function(event,ui){  
    if(!select)
    {
       $('ul.ui-autocomplete li:first a').trigger('click');
    }
    var data=$.data(this);//Get plugin data for 'this'
    console.log(data.autocomplete.selectedItem);
}
Aditya
  • 4,453
  • 3
  • 28
  • 39
  • The seletor `$('ul.ui-autocomplete li:first a')` not work while there are multi `autocomplete` tags. Simply fork from your DEMO: http://jsfiddle.net/6hfyb/ – andyf Apr 07 '14 at 02:34
  • Then you will have to make a a small change `$("#tags2").val($('ul.ui-autocomplete:eq(1) li:first a').text());` ,see here : **jsfiddle.net/draditya91/6hfyb/2** – Aditya Apr 07 '14 at 03:32
  • @Aditya how to get array objects text and value, let us say var args=[name:dog, val:1; name:cat, val:2; name:rat, val:3] – pappu_kutty Apr 08 '14 at 15:23
  • @Aditya , select function is not called on blur event, so i need to get item data inside blur , thanks – pappu_kutty Apr 08 '14 at 16:55
  • @Aditya I don't think using selector by index (`:eq(N)`) is a good idea. In some case when `autocomplete` tags are dynamically created, it's difficult to get the index number. – andyf Apr 09 '14 at 02:25
  • @Aditya what is the plugin i need to add, this is not working,getting Cannot read property 'selectedItem' of undefined – pappu_kutty Apr 09 '14 at 02:39
  • @pappu_kutty Load jquery UI 1.9.2 and that would solve the issue i think :) – Aditya Apr 09 '14 at 05:53
3

I think you are missing:

change: function( event, ui ) {}

http://api.jqueryui.com/autocomplete/

*untested

$( "#statelist" ).autocomplete({
                            change: function( event, ui ) {}
                            autoFocus: true,
                            source: states,
                            select: function (event, ui) {
                                    stateid = (ui.item.lable);
                                    $("#stateid").val(stateid);
                           },
                        }
   });
JBC
  • 112
  • 5
2

here i leave you a function already working for what you need getting the value on blur

I paste part of the code here

$( "#tags" ).autocomplete({
    source: availableTags,
    open: function(event, ui) { disable=true; },
    close: function(event, ui) { 
        disable=false; $(this).focus(); }
}).blur(function(){
    if(!disable){
        alert($(this).val());
    }
}); 

JsFiddle DEMO

alecellis1985
  • 131
  • 2
  • 15
2

Check this Fiddle .. This might helps you ...

Script

$( "#from" ).autocomplete({
    source: fromCity,
    select: function(event, ui) { 
        $( "#from" ).blur();        
        $( "#to" ).focus();
    }
});   
$( "#to" ).autocomplete({
    source: toCity
});    
Soundar
  • 2,569
  • 1
  • 16
  • 24
1

Please try this. It should work for you:

$('#statelist').autocomplete({
source: states,
autoFocus: true,
selectFirst: true,

open: function(event, ui) { if(select) select=false; },
    select: function(event, ui) { select=true; },

})

.live("blur", function(event) {
var get_val = $('ul.ui-autocomplete li:first a').text();

$('#stateid').val(get_val);
});
Neeraj Kumar
  • 506
  • 1
  • 8
  • 19
1

Tested solution It will force select first item if there is none Will work also when you first search in autocomplete and click over somewhere without even focusing on item list

Try this http://jsfiddle.net/killwithme/ke8osq27/

var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
   "BASIC",
   "C",
   "C++",
];

$("#tags").autocomplete({
    source: availableTags,
    autoFocus: true,
    selectFirst: true,
    select: function(event, ui) {
        $("#tags").val(ui.item.value);
        $("#tags-span").text(ui.item.value);
    }
}).on('autocompletechange', function() {
    if ($(this).data('ui-autocomplete').selectedItem === null) {
    //this will trigger your select automatically so it will handle other custom override you did for select
        $(this).data('ui-autocomplete').menu.element.children('li:first').children('a').trigger('click');
    }
});
0

To solve the issue described by @pappu_kutty in comment section of marked answer

"@andyf this is working as i expected, but one issue i found, let us say i entered "a" and items listed in dropdown i hover over list itmes and moved away from the list, in this case none of the items selected and autocomplete doesnt work :) – pappu_kutty"

add below code to autocomplete change event. It basically prevents any invalid choice in the autocomplete box.

change: function (event, ui) {
                if (ui.item == null) {
                    $(this).val('');
                    $(this).focus();
                    return;
                }
}
Ben M
  • 21
  • 1
0

Multiple autocompletes using @Aditya answer. After some researches the best I found has been to apply classes at the open method on the dropdown and using them to match the right dropdown.

Fiddle: http://jsfiddle.net/ac1fkr5w/2/

Code:

var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"];

var select = false;

$("#tags").autocomplete({
    source: availableTags,
    autoFocus: true,
    selectFirst: true,
    open: function(event, ui) {
    //Adding class
    $(this).data("uiAutocomplete").menu.element.addClass("tags");
    if(select) select=false; },
    select: function(event, ui) { select=true; }
}).blur(function(){
    if(!select)
    {
    //Using class to match the right ul
        $("#tags").val($('ul.tags li:first a').text());
    }
}); 


$("#tags2").autocomplete({
    source: availableTags,
    autoFocus: true,
    selectFirst: true,
    open: function(event, ui) {
    $(this).data("uiAutocomplete").menu.element.addClass("tags2");
    if(select) select=false;
    },
    select: function(event, ui) { select=true; }
}).blur(function(){
    if(!select)
    {
        $("#tags2").val($('ul.tags2 li:first a').text());
    }
});