When working on a project, the customer asked to be able to directly switch input (focus) with enter, and when the last one was reached, the information could be submitted directly.
The first idea is to copy a piece of code online and use it directly. But after searching on Baidu and Google, more than 80% of the codes found were the same. Some codes are too old and cannot be used. Some only work with some browsers. After struggling for half an hour, I still couldn't find a suitable solution. On last thought, I might as well do it myself.
1. Ideas
Every time you click Enter, get the current focus position, and then set its next element to get the focus;
2. Code
<script type="text/javascript"> $('input:text:first').focus(); document.onkeydown = function enterHandler(event) { var inputs = $("input"); //可自行添加其它过滤条件 var browser = navigator.appName ; //浏览器名称 var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 var Code = '' ; if(browser.indexOf('Internet')>-1) // IE Code = window.event.keyCode ; else if(userAgent.indexOf("Firefox")>-1) // 火狐 Code = event.which; else // 其它 Code = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; if (Code == 13) //可以自行加其它过滤条件 { 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 IE and Firefox obtain key values differently, a simple judgment is made on the browsers. This way you can get the key values you hit on each browser.
Finally, after obtaining the current value, you can add various other conditions.