С select2, как клавиша Enter действует как клавиша Tab, чтобы перейти к следующему элементу, и клавиша Enter + Shift, чтобы перейти назад. - PullRequest
2 голосов
/ 01 ноября 2019

Я борюсь с некоторыми проблемами. Надеюсь, что многие боссы ждут здесь в стеке переполнение , чтобы выручить меня от этих проблем.

Требование : я хочу, чтобы клавиша Enter действовала подобно клавише Tab, чтобы перейти к следующейelement и Enter + Shift для перехода назад элемента во всем проекте формы.

Он работает как очаровательный герой, как я написал код. Но когда я использую Select2, вставляющий несколько раз в форму, определяющую его общим классом CSS, это не работает так, как мне нужно.

Проблемы : он не фокусируется и не закрывается при нажатии клавиши ввода и не переходит к следующему элементу при выборе элемента.

Я видел множество подобных ссылок, которые я получил, но не получился.

<script type="text/javascript">
    
          //slect2 initialize here
            $(document).ready(function() {   
                $(".chosenCommon").select2({ width: '100%' });  
            });
            
            // Catch the keydown for the entire document
            $(document).keydown(function(e) {
            
              // Set self as the current item in focus
              var self = $(':focus'),
                // Set the form by the current item in focus
                form = self.parents('form:eq(0)'),
                focusable//,
               // next
                ;
            
              // Array of Indexable/Tab-able items   
              focusable = form.find('input:not([type="submit"],[type="reset"]),select,button,textarea,div[contenteditable=true]').filter(':visible:not([hidden],[readonly],[disabled], #save_btn, #update_btn, #delete_btn, #reset_btn):enabled');
            
              //next = focusable.eq(focusable.index(self)+1);  
              //alert(focusable.length);
            
              function enterKey()
              {
                if (e.which === 13 && !self.is('textarea')) 
                { 
                  // [Enter] key
            
                    // If not a regular hyperlink/button/textarea
                    if ( $.inArray(self, focusable) && (!self.is('a,button')) )
                    {
                        // Then prevent the default [Enter] key behaviour from submitting the form
                        e.preventDefault();
                    } // Otherwise follow the link/button as by design, or put new line in textarea
            
                    // Focus on the next item (either previous or next depending on shift)
                    var total = focusable.length;//alert(total);
                  var index = focusable.index(self);
            
                  if(e.shiftKey)
                  {
                    if(index > 0)
                    {
                      focusable.eq(index-1).focus();
                    }else{
                      focusable.eq(index).focus();
                    }
                  }else{
                    if(index < total)
                    {
                      focusable.eq(index+1).focus();
                    }else{
                      focusable.eq(index+total).focus();
                    }
            
                    // problem: slect an i tem from dropdown by pressing enter key it is not go to nex element
                    // alert(index);// -1
            
                    if(index==-1)
                    {
                      // what to do 
                    }
            
                  }
            
                  //focusable.eq( index + (e.shiftKey ? (index > 0 ? -1 :  0 ) : (index < total ? +1 : total ) ) ).focus();
            
                  //console.log(focusable);
                  
                  if( (total-1) == index)
                  {
                    //$("#save_btn").click();
                    //form.submit();
                  }   
            
                    return false;
                }
              }
            
              // We need to capture the [Shift] key and check the [Enter] key either way.
              if (e.shiftKey) { enterKey() } else { enterKey() }
            });
            </script>
            
            <form action="#">
        	
        	First name: <input type="text" name="FirstName" value="Mickey"><br>
        	Last name: <input type="text" name="LastName" value="Mouse"><br>
        
            <select class="chosenCommon" name="fruits">
                <option value="1">Banana</option>           
                <option value="2">Orange</option>
                <option value="3">Mango</option>
                
            </select>
        
            Full name: <input type="text" name="FullName" id="FullName" value="Mickey Mouse"><br>
        
            <input type="text" name="" id="address">
        
            <select class="chosenCommon" name="cities">
                <option value="1">Dhaka</option>           
                <option value="2">Chittagon</option>
                <option value="3">Rajshahi</option>
                <option value="3">Khulna</option>
            </select>
        
        	<input type="submit" value="Save" id="save_btn">
        </form>

1 Ответ

3 голосов
/ 11 ноября 2019

Попробуйте

e.keyCode и e.which устарели. Вы должны использовать e.key === "Enter". см. Здесь

FIDDLE DEMO

$('body').on('keydown', 'input, select', function(e) {
  if (e.shiftKey) {
    if (e.key === "Enter") {
      var self = $(this),
        form = self.parents('form:eq(0)'),
        focusable, next;
      focusable = form.find('input,a,select,button,textarea').filter(':visible');
      next = focusable.eq(focusable.index(this) - 1);
      if (next.length) {
        next.focus();
      } else {
        form.submit();
      }
      return false;
    }
  }
  if (e.key === "Enter") {
    var self = $(this),
      form = self.parents('form:eq(0)'),
      focusable, next;
    focusable = form.find('input,a,select,button,textarea').filter(':visible');
    next = focusable.eq(focusable.index(this) + 1);
    if (next.length) {
      next.focus();
    } else {
      form.submit();
    }
    return false;
  }
});

Обновленный ответ

Это захватит событие ввода ключа в select2

$(document).on('keyup', '.select2-search__field', function(e) {
  if (e.which === 13) {
    e.preventDefault();
    $('#example').select2("close");
    var inputs = $(this).closest('form').find(':input:visible');
    inputs.eq(inputs.index(this) + 1).focus();
  }
});

FIDDLE DEMO

...