Jeff Fabiny
Jeff Fabiny

Reputation: 325

jquery autoselect action on 'change' but not on 'select'

Hope that made sense. I have a text input that uses the jQuery UI autoselect feature. The input auto-fills when a user selects, as it should. My problem is if a user inputs something, but then doesn't select from the drop down. This results in the text input value being something that doesn't exist in the list upon a form submit. I want to know if there is a way to perform an action (clear text input value) on the 'change' event but leave it as it is for the 'select' event.

Upvotes: 1

Views: 465

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

If I'm understanding you correctly, you should be able to leverage the ui parameter that's passed to a change event handler:

$("#auto").autocomplete({
    /* options */
    change: function (event, ui) {
        if (!ui.item) {
            this.value = '';
        }
    }
});

ui.item will be undefined if nothing is selected from the autocomplete candidate list.

Example: http://jsfiddle.net/ZBzpF/

Upvotes: 1

cjc343
cjc343

Reputation: 3765

Inside the change event handler, check if the current value is in the source, if not, reset it. Something like:

var sourceArray = ["a", "b", "c"],
$autocomplete = $('#autocomplete');
$autocomplete.autocomplete({
    source: ,
    change: function(e, ui) {
        if ($.inArray($autocomplete.val(), sourceArray) === -1) {
            //change the value
        }
    })
}

Upvotes: 0

Related Questions