Enter key press behaves like a Tab in Javascript

后端 未结 22 1170
说谎
说谎 2020-11-27 10:52

I\'m looking to create a form where pressing the enter key causes focus to go to the \"next\" form element on the page. The solution I keep finding on the web is...

相关标签:
22条回答
  • 2020-11-27 11:37

    If you can I would reconsider doing this: the default action of pressing <Enter> while in a form submits the form and anything you do to change this default action / expected behaviour could cause some usability issues with the site.

    0 讨论(0)
  • 2020-11-27 11:39

    Here is an angular.js directive to make enter go to the next field using the other answers as inspiration. There is some, perhaps, odd looking code here because I only use the jQlite packaged with angular. I believe most of the features here work in all browsers > IE8.

    angular.module('myapp', [])
    .directive('pdkNextInputOnEnter', function() {
        var includeTags = ['INPUT', 'SELECT'];
    
        function link(scope, element, attrs) {
            element.on('keydown', function (e) {
                // Go to next form element on enter and only for included tags
                if (e.keyCode == 13 && includeTags.indexOf(e.target.tagName) != -1) {
                    // Find all form elements that can receive focus
                    var focusable = element[0].querySelectorAll('input,select,button,textarea');
    
                    // Get the index of the currently focused element
                    var currentIndex = Array.prototype.indexOf.call(focusable, e.target)
    
                    // Find the next items in the list
                    var nextIndex = currentIndex == focusable.length - 1 ? 0 : currentIndex + 1;
    
                    // Focus the next element
                    if(nextIndex >= 0 && nextIndex < focusable.length)
                        focusable[nextIndex].focus();
    
                    return false;
                }
            });
        }
    
        return {
            restrict: 'A',
            link: link
        };
    });
    

    Here's how I use it in the app I'm working on, by just adding the pdk-next-input-on-enter directive on an element. I am using a barcode scanner to enter data into fields, the default function of the scanner is to emulate a keayboard, injecting an enter key after typing the data of the scanned barcode.

    There is one side-effect to this code (a positive one for my use-case), if it moves focus onto a button, the enter keyup event will cause the button's action to be activated. This worked really well for my flow as the last form element in my markup is a button that I want activated once all the fields have been "tabbed" through by scanning barcodes.

    <!DOCTYPE html>
    <html ng-app=myapp>
      <head>
          <script src="angular.min.js"></script>
          <script src="controller.js"></script>
      </head>
      <body ng-controller="LabelPrintingController">
          <div class='.container' pdk-next-input-on-enter>
              <select ng-options="p for p in partNumbers" ng-model="selectedPart" ng-change="selectedPartChanged()"></select>
              <h2>{{labelDocument.SerialNumber}}</h2>
              <div ng-show="labelDocument.ComponentSerials">
                  <b>Component Serials</b>
                  <ul>
                      <li ng-repeat="serial in labelDocument.ComponentSerials">
                          {{serial.name}}<br/>
                          <input type="text" ng-model="serial.value" />
                      </li>
                  </ul>
              </div>
              <button ng-click="printLabel()">Print</button>
          </div>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-11-27 11:40

    You can use my code below, tested in Mozilla, IE, and Chrome

       // Use to act like tab using enter key
        $.fn.enterkeytab=function(){
             $(this).on('keydown', 'input, select,', function(e) {
            var self = $(this)
              , form = self.parents('form:eq(0)')
              , focusable
              , next
              ;
                if (e.keyCode == 13) {
                    focusable = form.find('input,a,select,button').filter(':visible');
                    next = focusable.eq(focusable.index(this)+1);
                    if (next.length) {
                        next.focus();
                    } else {
                        alert("wd");
                        //form.submit();
                    }
                    return false;
                }
            });
    
        }
    

    How to Use?

    $("#form").enterkeytab(); // enter key tab

    0 讨论(0)
  • 2020-11-27 11:40

    I had a simular need. Here is what I did:

      <script type="text/javascript" language="javascript">
        function convertEnterToTab() {
          if(event.keyCode==13) {
            event.keyCode = 9;
          }
        }
        document.onkeydown = convertEnterToTab;    
      </script>  
    
    0 讨论(0)
提交回复
热议问题