jQuery UI Autocomplete: How to get 'change' event to fire earlier?
Asked Answered
D

1

14

http://jqueryui.com/demos/autocomplete/#event-change

It sounds like the change event is supposed to fire after you've selected an item, but instead it seems to fire onblur, but only if the input has changed.

select OTOH fires too early, it fires before the input text gets updated.

I want to do something with the input as soon as the user picks an item OR after the user types something and switches focus (like the usual change event).

How can I do that?

Demoralize answered 20/6, 2011 at 4:20 Comment(5)
the documentation states that the newly selected value is referred to by ui.item. Could you get the value that way? The change item also fires always after the close event which is what you mentioned about not firing until the onblur event.Wideangle
@Ben: The close event gets fired before onblur. Yes, I could take advantage of ui.item but then I'd have to treat the 2 cases where the user types something to cause a change, and where the user selects an item, differently (have to access the data differently). Unless we cheat...like I did. But now that you mention it, the data seems to get updated before the close event fires, so I could also trigger the change there.Demoralize
It's funny it says "When the list is hidden - doesn't have to occur together with a change." because those 2 events do not fire at the same time, even when they both occur.Demoralize
I realise that the close event fires before onblur I thought maybe you had thought they were related because you were clicking away which would obviously cause both events to be fired. Nice solution below, glad you figured it out.Wideangle
@Ben: Well yes, I did think they would fire one immediately after the other. i.e., when you click on an item, I'd expect the close event to fire, immediately followed by change event. But that's not what happens. The close event fires, and then the change event doesn't fire until you click somewhere else. Oh well. I love events, but I hate when there's a hole where the event you actually want is.Demoralize
D
21

Nevermind, figured it out. We can cheat:

select: function(event,ui) { 
    this.value=ui.item.value; 
    $(this).trigger('change'); 
    return false; 
}

Set the value of the input manually, then trigger the change event manually, and return false so that it doesn't bother setting the input twice.

Demoralize answered 20/6, 2011 at 4:25 Comment(1)
you've saved me from a nervous breakdown! thank you!Dochandorrach

© 2022 - 2024 — McMap. All rights reserved.