Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ui autocomplete enter key to add to the list

I have an input box similar to this http://jqueryui.com/demos/autocomplete/#multiple with the add button. I want to add all values split by comma added to a list on enter. I can't manage to do this because the keypress with enter seems to be conflict with select event of autocomplete. The problem is that the user can add only one item. I want the user to add multiple items then press enter key to add them to the list at the same time.

The enter key event should happen only when the suggestion list of autocomplete is closed.

like image 507
Chamnap Avatar asked Sep 01 '12 15:09

Chamnap


2 Answers

You can use the open and close events of autocomplete to keep track whether or not the suggestion list is currently open (storing this information somewhere - in the example below, in the "selectVisible" data):

$( "#tags" )
    .bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.ENTER && !$(this).data("selectVisible") ) {
            // Your code
        }
        ...
    })
    .autocomplete({
        open: function() {
            $(this).data("selectVisible", true);
        },
        close: function() {
            $(this).data("selectVisible", false);
        },
        ...
    });

Working example at jsFiddle.

like image 53
mgibsonbr Avatar answered Dec 31 '22 18:12

mgibsonbr


I've used the jQuery Multiselect widget with great success before and I believe it is more intuitive to the user that they can select multiple options.

Also it handles the Enter key appropriately out of the box.

http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/

like image 41
rbj325 Avatar answered Dec 31 '22 19:12

rbj325