Search code examples
jqueryjquery-select2jquery-select2-4

How to focus select2 pressing enter key?


I am attempting to do an AJAX call with the Select2 ver4 jquery plugin and Using Loading remote data of Select2 sample page. Now I try to pressing enter key next element focus.

HTML CODE

<table>
    <tr>
        <td>
            <select class="rp">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
        </td>
        <td>
           <select class="rp">
               <option value="1">1</option>
               <option value="2">2</option>
           </select>
        </td>
        <td>
            <select class="js-example-data-array"></select>
        </td>
    </tr>
</table>

JS CODE

$('select:first').focus();

$('input, select, textarea').on('keydown', function(e) {
    if (e.which == 13) {
        if (e.ctrlKey) {
                $(this).closest('form').submit();
            } else {
                var fields = $(this).closest('form').find('input, select, textarea');
                var total = fields.length;
                var index = fields.index(this);
                fields.eq( index + (e.shiftKey ? (index > 0 ? -1 :  0 ) : (index < total ? +1 : total ) ) ).focus();
                return false;
            }
        }
    });

var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
$(".js-example-data-array").select2({
    data: data
})

https://jsfiddle.net/ojpcsyxd/

I want to focus next element by pressing enter key. But I can't focus select2 element.


Solution

  • $(".js-example-data-array").select2('open');
    

    This will focus the select2.