Submit another form on enter key


I have integrated 4.0.8 version in my project and wants to achieve two things.

  1. When drop-down is appearing and user click on an option user will be redirected to the URL given in extra attribute of option, i made the changes in “templateSelection” and it is working correctly.

  2. My second option is if users enter some text and press enter key after/before appearing drop-down list, there is form on the page which should be submitted and its default behavior (redirected to other page) should stopped. This working correctly when user hit enter key before options appear but when option is available it is always picking the first option and user is redirected to other page and my form is not submitted. Here is code i used:

              ajax: {
                 url: 'index.php',
                 dataType: 'json',
                 delay: 1000,
                 data: function (params) {
                    var queryParameters = {
                       searchTerm: params.term
                    return queryParameters;
                 processResults: function (data) {
                    var resultArray = [];
                    jQuery.each(data, function(i, v) {
                       let url = 'someurl';
                    return {
                       results: resultArray
                 cache: true
              placeholder: 'Search...',
              minimumInputLength: 2,
              templateResult: formatResult,
              allowClear: true,
              templateSelection: formatResultSelection
    function formatResult (result) {
       if (result.loading) {
          return result.text;
        return "formated result";
    function formatResultSelection (data) {
        if(data.url) {
           var location = data.url;
           if(location && location!='#') window.location = location;
       return || data.text;
    jQuery("#text_Search").on("keydown", function (e) {
          if (e.keyCode == 13) {
             let searchTxt = jQuery(".select2-search__field").val();


The Select2 is working correctly. When the dropdown appears, the Select2 has keyboard focus and the Enter key selects the currently highlighted item in the dropdown.

As far as I can tell, there is no way to change this, mainly because you cannot detect the Enter keypress before Select2 makes its selection (the select2:selecting event, which can be cancelled, fires before any keydown handler you install).

The only way to change this behavior is to modify the Select2 source code yourself. Here is the relevant file: The keypress handler starts on line 328, and the Enter key handling code is on lines 337–340.