Home > front end >  JQuery empty input not working with .val('');
JQuery empty input not working with .val('');

Time:06-08

I have a function that works in my JQuery autocomplete.

The function itself seems to work, but when selecting from autocomplete list, the line to empty the input is not working.

I re-created the issue here:

http://jsfiddle.net/bv8nr2gp/1/

Everything works, except the line $('#' x).val('');

UPDATE

I've updated the fiddle to include the missing elements.

If you enter a value in the input field and click Add it works. The value is added to the textarea and span and then removed from the input.

If you enter "one" or "two" in the input and choose it from the autocomplete list, it works apart from clearing the input

CodePudding user response:

The issue is that you're clearing the input before the autocomplete has completed.

From jquery-ui (with emphasis):

select( event, ui )

Triggered when an item is selected from the menu.
The default action is to replace the text field's value with the value of the selected item.
Cancelling this event prevents the value from being updated, but does not prevent the menu from closing.

The process is:

  • auto-complete select event
  • which calls your add function which clears the input
  • auto-complete then sets the input to the selected value as part of the autocomplete process

You can cancel the autocomplete select so that it doesn't update the input:

    select: function(event, ui) {
      addEmailContact(this.id, ui.item.value);
      event.preventDefault();
    }
  • Related