53

How do you trigger jQuery UI's AutoComplete change event handler programmatically?

Hookup

$("#CompanyList").autocomplete({ 
    source: context.companies, 
    change: handleCompanyChanged 
});

Misc Attempts Thus Far

$("#CompanyList").change();
$("#CompanyList").trigger("change");
$("#CompanyList").triggerHandler("change");

Based on other answers it should work:

How to trigger jQuery change event in code

jQuery Autocomplete and on change Problem

JQuery Autocomplete help

The change event fires as expected when I manually interact with the AutoComplete input via browser; however I would like to programmatically trigger the change event in some cases.

What am I missing?

Ganesh Yadav
  • 2,607
  • 2
  • 29
  • 52
Chris Baxter
  • 16,083
  • 9
  • 51
  • 72

14 Answers14

46

Here you go. It's a little messy but it works.

$(function () {  
  var companyList = $("#CompanyList").autocomplete({ 
      change: function() {
          alert('changed');
      }
   });
   companyList.autocomplete('option','change').call(companyList);
});
John Kalberer
  • 5,690
  • 1
  • 23
  • 27
23

this will work,too

$("#CompanyList").autocomplete({
  source : yourSource,
  change : yourChangeHandler
})

// deprecated
//$("#CompanyList").data("autocomplete")._trigger("change")
// use this now
$("#CompanyList").data("ui-autocomplete")._trigger("change")
lordvlad
  • 5,200
  • 1
  • 24
  • 44
  • 2
    @lordvlad when i try to call change event the error connsole says $().data is undefined. – Mihir Jul 04 '13 at 17:39
  • @Mihir could be that they changed something in their new version. you could still have a look into the sourcecode, to try and find a way. thats how i found it out. good luck and maybe you can share your answer. – lordvlad Jul 04 '13 at 21:23
  • 1
    @lordvlad it seem's that currently `.data('autocomplete')` should be changed into `elem.data("ui-autocomplete");` (as Chris Kinsella told it in his answer). IMO your answer is better than the marked one because we have access to `event` and `ui` arguments of the `change` function. – akn Mar 16 '15 at 14:34
19

It's better to use the select event instead. The change event is bound to keydown as Wil said. So if you want to listen to change on selection use select like that.

$("#yourcomponent").autocomplete({  
    select: function(event, ui) {
        console.log(ui);
    }
});
Mark Carpenter Jr
  • 812
  • 1
  • 16
  • 32
user1484668
  • 253
  • 2
  • 8
13

They are binding to keydown in the autocomplete source, so triggering the keydown will case it to update.

$("#CompanyList").trigger('keydown');

They aren't binding to the 'change' event because that only triggers at the DOM level when the form field loses focus. The autocomplete needs to respond faster than 'lost focus' so it has to bind to a key event.

Doing this:

companyList.autocomplete('option','change').call(companyList);

Will cause a bug if the user retypes the exact option that was there before.

Will Shaver
  • 12,471
  • 5
  • 49
  • 64
  • Actually I think he was trying to just trigger the change event, which triggers after loosing focus, not the one that drops down the list. – Kelly Elton Mar 06 '12 at 06:22
  • @kelton52 I believe he was mistakenly thinking that the autocomplete widget would use the change event, which it does not. Triggering keydown in turn calls the internal _searchTimeout which is what he's really wanting to do: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.autocomplete.js#L127 – Will Shaver Mar 21 '12 at 21:14
  • Well it does call the change event when it loses focus – Kelly Elton Mar 22 '12 at 19:09
  • OP wants to trigger the widget's internal change event, as set by the `change` option, which is separate from the JS change event. – Potatoswatter May 15 '12 at 02:43
  • 1
    +1 for telling autocompletechange is triggered on keydown.This is the solution.Nice work! Please make this as the answer – human.js Jun 04 '12 at 10:12
  • Used $(this).trigger('keydown') in select: for autocomplete.But it was not triggering the text field (for autocomplete) .change event. What could be wrong here? – user938363 Oct 27 '12 at 15:22
  • Just a note: do not subscribe on keydown eva'. You will loose the last typed character! Use keyup instead. – zsitro Mar 26 '13 at 14:07
  • I tried doing this before Googling to this page. It does not work and neither does "keyup", "keypress", "change", "autocompletechange" nor focus(). – Steven Vachon Jul 12 '13 at 19:16
  • This works: http://stackoverflow.com/questions/4917195/how-to-get-jquery-autocomplete-to-pop-up-on-field-focus – Steven Vachon Jul 12 '13 at 19:33
10

Here is a relatively clean solution for others looking up this topic:

// run when eventlistener is triggered
$("#CompanyList").on( "autocompletechange", function(event,ui) {
   // post value to console for validation
   console.log($(this).val());
});

Per api.jqueryui.com/autocomplete/, this binds a function to the eventlistener. It is triggered both when the user selects a value from the autocomplete list and when they manually type in a value. The trigger fires when the field loses focus.

Skyhawk637
  • 101
  • 1
  • 3
  • The question was how to programmatically trigger that handler, not how to define it. This is just an alternate way of defining it. – Tim Tisdall Dec 01 '17 at 15:35
3

You have to manually bind the event, rather than supply it as a property of the initialization object, to make it available to trigger.

$("#CompanyList").autocomplete({ 
    source: context.companies
}).bind( 'autocompletechange', handleCompanyChanged );

then

$("#CompanyList").trigger("autocompletechange");

It's a bit of a workaround, but I'm in favor of workarounds that improve the semantic uniformity of the library!

Ganesh Yadav
  • 2,607
  • 2
  • 29
  • 52
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
3

The programmatically trigger to call the autocomplete.change event is via a namespaced trigger on the source select element.

$("#CompanyList").trigger("blur.autocomplete");

Within version 1.8 of jquery UI..

.bind( "blur.autocomplete", function( event ) {
    if ( self.options.disabled ) {
        return;
    }

    clearTimeout( self.searching );
    // clicks on the menu (or a button to trigger a search) will cause a blur event
    self.closing = setTimeout(function() {
        self.close( event );
        self._change( event );
    }, 150 );
});
Ganesh Yadav
  • 2,607
  • 2
  • 29
  • 52
Peter O Brien
  • 105
  • 2
  • 6
3

The simplest, most robust way is to use the internal ._trigger() to fire the autocomplete change event.

$("#CompanyList").autocomplete({
  source : yourSource,
  change : yourChangeHandler
})

$("#CompanyList").data("ui-autocomplete")._trigger("change");

Note, jQuery UI 1.9 changed from .data("autocomplete") to .data("ui-autocomplete"). You may also see some people using .data("uiAutocomplete") which indeed works in 1.9 and 1.10, but "ui-autocomplete" is the official preferred form. See http://jqueryui.com/upgrade-guide/1.9/#changed-naming-convention-for-data-keys for jQuery UI namespaecing on data keys.

  • Rather than being a separate answer, the change referenced to `ui-autocomplete` could have been a comment on the answer from @lordvlad – Chris Baxter Dec 06 '13 at 23:07
2

I was trying to do the same, but without keeping a variable of autocomplete. I walk throught this calling change handler programatically on the select event, you only need to worry about the actual value of input.

$("#CompanyList").autocomplete({ 
    source: context.companies, 
    change: handleCompanyChanged,
    select: function(event,ui){
        $("#CompanyList").trigger('blur');
        $("#CompanyList").val(ui.item.value);
        handleCompanyChanged();
    }
});
Ganesh Yadav
  • 2,607
  • 2
  • 29
  • 52
Perazzo
  • 1,127
  • 13
  • 24
1

Well it works for me just binding a keypress event to the search input, like this:

... Instantiate your autofill here...

    $("#CompanyList").bind("keypress", function(){
    if (nowDoing==1) {
        nowDoing = 0;
        $('#form_459174').clearForm();
    }        
});
jdisla
  • 139
  • 6
0
$('#search').autocomplete( { source: items } );
$('#search:focus').autocomplete('search', $('#search').val() );

This seems to be the only one that worked for me.

  • 1
    `$("#search:focus").autocomplete("search")` will do. http://stackoverflow.com/questions/4917195/how-to-get-jquery-autocomplete-to-pop-up-on-field-focus – Steven Vachon Jul 12 '13 at 19:34
0

This post is pretty old, but for thoses who got here in 2016. None of the example here worked for me. Using keyup instead of autocompletechange did the job. Using jquery-ui 10.4

$("#CompanyList").on("keyup", function (event, ui) {
    console.log($(this).val());
});

Hope this help!

Merlin
  • 4,907
  • 2
  • 33
  • 51
0

Another solution than the previous ones:

//With trigger
$("#CompanyList").trigger("keydown");

//With the autocomplete API
$("#CompanyList").autocomplete("search");

jQuery UI Autocomplete API

https://jsfiddle.net/mwneepop/

Kaymaz
  • 454
  • 8
  • 23
  • Can you elaborate more about this? Because this one should be not working since autocomplete is not keyup. I tried that before, but please elaborate it on how it could works. – ksugiarto May 12 '16 at 08:04
  • Edited my answer: it was not `keyup` but `keydown`. – Kaymaz May 15 '16 at 14:15
0
$("#CompanyList").trigger('keydown');

works outside of autocomplete.

Marsad
  • 859
  • 1
  • 14
  • 35