jquery ui autocomplete: trigger only when item is not selected
Asked Answered
K

1

5

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.

Khadijahkhai answered 16/9, 2011 at 16:38 Comment(2)
When I run this, it shows keys as I type, but if I select a value it doesn't show any key press events, even using the arrow keys. Please clarify the issue, or at least tell me what the ultimate usage of this is so I can better understand how to help.Furbish
I'll change it to alert. Console.log is for firebug. Also make your entries with the "enter" key.Khadijahkhai
E
10

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/

Euphonious answered 17/9, 2011 at 1:51 Comment(1)
That would work great if I could trigger the change event with keypress enter and dynamic data source. But best answer here, and I didn't mention anything about the data source.Khadijahkhai

© 2022 - 2024 — McMap. All rights reserved.