jQuery AutoComplete Trigger Change Event
Asked Answered
C

14

54

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?

Cyrille answered 21/6, 2011 at 20:18 Comment(0)
D
47

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);
});
Dovetail answered 21/6, 2011 at 20:30 Comment(2)
Working trumps messy; and this definitely isn't too bad. Thanks for the help. Is that documented somewhere?Cyrille
No, I think it should be though (or a better way to trigger these events). I have just run into this in the past.Dovetail
A
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")
Amoral answered 6/9, 2012 at 12:14 Comment(3)
@Amoral when i try to call change event the error connsole says $().data is undefined.Malissa
@Malissa 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.Amoral
@Amoral 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.Cornia
L
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);
    }
});
Lincolnlincolnshire answered 24/6, 2013 at 13:47 Comment(4)
Why isn't this the most popular solution??Correspond
This is by far the best solution.Vizierate
This is actual solution. view this implemented code. jsfiddle.net/arjunarora208/t6ehkL5bFreeway
I think the question is how to trigger this select: function to fire programmatically, without the user actually clicking on the choice.Congregational
P
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.

Procopius answered 30/1, 2012 at 20:44 Comment(9)
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.Ledda
@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: github.com/jquery/jquery-ui/blob/master/ui/…Procopius
Well it does call the change event when it loses focusLedda
OP wants to trigger the widget's internal change event, as set by the change option, which is separate from the JS change event.Wilkison
+1 for telling autocompletechange is triggered on keydown.This is the solution.Nice work! Please make this as the answerMonicamonie
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?Exarch
Just a note: do not subscribe on keydown eva'. You will loose the last typed character! Use keyup instead.Alcorn
I tried doing this before Googling to this page. It does not work and neither does "keyup", "keypress", "change", "autocompletechange" nor focus().Thuggee
This works: #4917695Thuggee
C
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.

Candidacandidacy answered 6/1, 2015 at 21:51 Comment(1)
The question was how to programmatically trigger that handler, not how to define it. This is just an alternate way of defining it.Metage
W
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!

Wilkison answered 15/5, 2012 at 2:47 Comment(0)
M
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 );
});
Michelson answered 11/7, 2012 at 17:7 Comment(0)
T
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.

Tedman answered 6/12, 2013 at 21:53 Comment(1)
Rather than being a separate answer, the change referenced to ui-autocomplete could have been a comment on the answer from @AmoralCyrille
P
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();
    }
});
Picky answered 6/9, 2013 at 16:4 Comment(0)
J
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();
    }        
});
Jeer answered 16/8, 2012 at 17:51 Comment(0)
C
0
$('#search').autocomplete( { source: items } );
$('#search:focus').autocomplete('search', $('#search').val() );

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

Cornstalk answered 3/6, 2013 at 4:43 Comment(1)
$("#search:focus").autocomplete("search") will do. #4917695Thuggee
R
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!

Ruffled answered 11/1, 2016 at 10:29 Comment(0)
P
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/

Polyanthus answered 11/5, 2016 at 12:46 Comment(2)
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.Loyceloyd
Edited my answer: it was not keyup but keydown.Polyanthus
H
0
$("#CompanyList").trigger('keydown');

works outside of autocomplete.

Horsetail answered 14/4, 2023 at 17:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.