Clear form field after select for jQuery UI Autocomplete
        Posted  
        
            by jonfhancock
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by jonfhancock
        
        
        
        Published on 2010-04-01T16:20:28Z
        Indexed on 
            2010/04/01
            16:23 UTC
        
        
        Read the original article
        Hit count: 615
        
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.
© Stack Overflow or respective owner