Nick Olsen Nick Olsen - 2 years ago 274
Javascript Question

jQuery UI Autocomplete: Clear Previous Search Term

On the keydown event of the jQuery UI Autocomplete widget the default case statement has the following code:

// keypress is triggered before the input value is changed
clearTimeout( self.searching );
self.searching = setTimeout(function() {
// only search if the value has changed
if ( self.term != self.element.val() ) {
self.selectedItem = null; null, event );
}, self.options.delay );

From what I can see the sixth line of the above code prevents execution if the user types in the same value twice. This makes sense most of the time but in my scenario it is causing a problem.

I am building an ajax application that has a fixed header with a search input at the top. The user can type in anything they want into the search box and a div will pop up with the search results matching their query. If the user types in 'abc' and clicks on a result, it loads the corresponding page via ajax and clears the search box. The problem is that if they user types in 'abc' again, the search method is not fired as what they typed in matches what they last searched for.

Is there a way to clear the self.term value stored within the widget when the user clicks on a search result? Or is there another way to resolve my problem without having to cook up my own version of the Autocomplete widget?


Answer Source

Doing the following resets the previous search term:

 $('#AutocompleteElementID').data().autocomplete.term = null;

If you do the following when an item is selected, it will clear the previous search term and make the widget perform a search if they type in the same value again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download