Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear form field after select for jQuery UI Autocomplete

I'm developing a form, and using jQuery UI Autocomplete. When the user selects an option, I want the selection to pop into a span appended to the parent <p> tag. Then I want the field to clear rather than be populated with the selection.

I have the span appearing just fine, but I can't get the field to clear.

How do you cancel jQuery UI Autocomplete's default select action?

Here is my code:

var availableTags = ["cheese", "milk", "dairy", "meat", "vegetables", "fruit", "grains"]; $("[id^=item-tag-]").autocomplete({     source: availableTags,      select: function(){         var newTag = $(this).val();         $(this).val("");         $(this).parent().append("<span>" + newTag + "<a href=\"#\">[x]</a> </span>");     } }); 

Simply doing $(this).val(""); doesn't work. What is maddening is that almost the exact function works fine if I ignore autocomplete, and just take action when the user types a comma as such:

$('[id^=item-tag-]').keyup(function(e) {     if(e.keyCode == 188) {         var newTag = $(this).val().slice(0,-1);         $(this).val('');         $(this).parent().append("<span>" + newTag + "<a href=\"#\">[x]</a> </span>");     } }); 

The real end result is to get autocomplete to work with multiple selections. If anybody has any suggestions for that, they would be welcome.

like image 553
Jon F Hancock Avatar asked Apr 01 '10 16:04

Jon F Hancock


People also ask

How do you clear autocomplete value?

You can use material ui autocomplete's default prop filterSelectedOptions . If true, it will hide the selected options from the list box. For clearing the values of autocomplete, it gives default clear icon at the end of the select box. you can clear it from there.

How does autocomplete work in jquery?

The autocomplete (options) method declares that an HTML <input> element must be managed as an input field that will be displayed above a list of suggestions. The options parameter is an object that specifies the behavior of the list of suggestions when the user is typing in the input field.

What is JavaScript autocomplete?

The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are tags for programming languages, give "ja" (for Java or JavaScript) a try. The datasource is a simple JavaScript array, provided to the widget using the source-option.


1 Answers

Add $(this).val(''); return false; to the end of your select function to clear the field and cancel the event :)

This will prevent the value from being updated. You can see how it works around line 109 here.

The code in there checks for false specifically:

if ( false !== self._trigger( "select", event, { item: item } ) ) {   self.element.val( item.value ); } 
like image 180
Nick Craver Avatar answered Sep 18 '22 12:09

Nick Craver