After selection, prevent input value from being restored to search term

Hi,

I am creating a ‘Quick Orders’ section.
The input field, which is used for the autocomplete, gets populated with the selected suggestion SKU, upon selected from dropdown.

$('.quickorders-autocomplete')
                .autocomplete(options, source)
                .on('autocomplete:selected', function (e,suggestion,dataset) {
                    jQuery(e.currentTarget).val(suggestion.sku);
                    e.preventDefault();
                });

However, after the dropdown removes, the input value is again restored to that which was searched.

How do I prevent the autocomplete action that restores that input back to the searched value, leaving the value I populated after selection?

I placed a small video showing the issue.video shows the issue

Hi Lucas,

You should use the val method of the autocomplete object instead of the jQuery function.
See here: https://github.com/algolia/autocomplete.js/#jqueryautocompleteval-val

So this code should work:

$('.quickorders-autocomplete')
                .autocomplete(options, source)
                .on('autocomplete:selected', function (e,suggestion,dataset) {
                    jQuery(e.currentTarget).autocomplete('val', suggestion.sku);
                    e.preventDefault();
                });

Hi,

Thanks, close, but put me on teh right track.
The event target element does not have autocomplete (which resulted in error of .autocomplete is not a function)

Adjusting the code as follows made it work:

$('.quickorders-autocomplete')
                .autocomplete(options, source)
                .on('autocomplete:selected', function (e,suggestion,dataset) {
                    $(this).autocomplete('val', suggestion.sku);
                    e.preventDefault();
                });

So one last issue, with solution for in case anyone needs this help.

As soon as I change the value using $(this).autocomplete(‘val’, suggestion.sku); a new autocomplete results.
This is obviously not wanted.

I solved this by placing a new class called ‘no-autocomplete’ to the element, and then a focus event to remove it, making it ready for any next required lookup.

$('.quickorders-autocomplete')
                .autocomplete(options, source)
                .on('autocomplete:selected', function (e, suggestion, dataset) {
                    $(this).autocomplete('val', suggestion.sku).addClass('no-autocomplete');
                }).on('focus', function (e) {
                    $(this).removeClass('no-autocomplete');
            });

Potentially other solution to this?