capturing enter key in select2

Viewed 25369

I'm using select2 to present an editable selectbox. When user writes a statement which does not appear in the list(select2, data), I show a button to add this statement to the list.

Forcing users to click the button seems to me a little bit frustration. Is it possible to capture enter key in select2? I want to make user able to add his/her new statements into the list just by pressing enter key.

5 Answers

I'm using Select2 4.0.3 and this works form me:

$(document).on('keyup', '.select2-search__field', function (e) {
    if (e.which === 13) {
        alert('Pressed enter!');
    }
});

None of these worked in Select2 4.0.6-rc1, but this did:

$('#mySelect2').on('select2:select', function (e) {
    var data = e.params.data;
    console.log(data);
});

It's detailed in the manual here.

Related