Jquery to achieve compatibility with the browser's Enter return switch input focus method

  • 2020-03-30 03:47:47
  • OfStack

When working on a project, the client asked to be able to use the enter enter to switch the input (focus) directly, and when the last one, to submit the information directly.

The first idea is to copy a piece of code online. But baidu, Google looked for a time, found more than 80% of the code is the same. Some of the code is too old to work. Some browsers work with only a few. After half an hour, I couldn't find a proper solution. Finally, do it yourself.

A, thinking

Each time you click enter, get the current focus position, and then set its next element to get focus;

Second, the code


<script type="text/javascript">
 $('input:text:first').focus(); 
 document.onkeydown = function enterHandler(event)
 {
   var inputs = $("input");           //You can add other filtering conditions
   var browser = navigator.appName ;      //Browser name
   var userAgent = navigator.userAgent;     //Gets the userAgent string for the browser
   
   var Code = '' ;
   if(browser.indexOf('Internet')>-1)      // IE  
    Code = window.event.keyCode ;
   else if(userAgent.indexOf("Firefox")>-1)   //  firefox 
    Code = event.which;
   else                     //  other 
     Code = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  
   if (Code == 13)               //You can add other filtering conditions
   {
     for(var i=0;i<inputs.length;i++)
     {
      if(inputs[i].id == document.activeElement.id)
      {  
        i = i== (inputs.length - 1) ? -1 : i ;
        $('#'+ inputs[i+1].id ).focus()
        break;
      }
     }
   }
 }

</script>

  Among them, because the key value of Internet explorer and firefox to get different, so the browser made a simple distinction. This allows you to retrieve the key hit on each browser.

Finally, once you get the current value, you can add the other conditions.

Demo address: (link: http://demo.jb51.net/js/2014/jsenterqiehuan/)


Related articles: