Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ui autocomplete: trigger only when item is not selected

I'm trying to figure out how to make an "opposite" of a jquery ui select. When someone does not select an option and just types "jquery something" output will be: "new input: jquery something". However when the "jquery" is selected it would be nice to somehow only have "selected from list: jquery", and prevent the keypress propogation. However, both events fire. I'm trying to make it one or the other.

<input class="test" type="text" />

<script>
$('.test').autocomplete({
    select: function (event, ui) {
        alert('selected from list: ' + ui.item.label);
        event.preventDefault();
        return false;
    },
    source: ["jquery", "jquery ui", "sizzle"]
});
$('.test').live('keypress', function (e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        alert('new input: ' + $(this).val());
    }
});
</script>

This is going with the assumption that the "enter" key is used to select an option from the ui's menu.

like image 352
Parmenides Avatar asked Sep 16 '11 16:09

Parmenides


1 Answers

You could accomplish this using the autocompletechange event. Using this event, you can determine if the user selected an option or typed something in that wasn't on the list:

$("#auto").autocomplete({
    source: ['hi', 'bye', 'foo', 'bar'],
    change: function(event, ui) {
        console.log(this.value);
        if (ui.item == null) {
            $("span").text("new item: " + this.value);
        } else {
            $("span").text("selected item: " + ui.item.value);
        }
    }
});

Example: http://jsfiddle.net/Ne9FH/

like image 119
Andrew Whitaker Avatar answered Sep 28 '22 05:09

Andrew Whitaker