Clear form field after select for jQuery UI Autocomplete
return false is needed within the select callback, to empty the field. but if you want to again control the field, i.e. set the value, you have to call a new function to break out of the ui.
Perhaps you have a prompt value such as :
var promptText = "Enter a grocery item here."
Set it as the element's val. (on focus we set to '').
$("selector").val(promptText).focus(function() { $(this).val(''); }).autocomplete({
source: availableTags,
select: function(){
$(this).parent().append("<span>" + ui.item.value + "<a href=\"#\">[x]</a> </span>");
foo.resetter(); // break out //
return false; //gives an empty input field //
}
});
foo.resetter = function() {
$("selector").val(promptText); //returns to original val
}
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 );
}
Instead of return false you could also use event.preventDefault().
select: function(event, ui){
var newTag = $(this).val();
$(this).val("");
$(this).parent().append("<span>" + newTag + "<a href=\"#\">[x]</a> </span>");
event.preventDefault();
}