Home > Web Front-end > JS Tutorial > Enter to switch input focus implementation ideas and code compatible with major browsers_jquery

Enter to switch input focus implementation ideas and code compatible with major browsers_jquery

WBOY
Release: 2016-05-16 16:37:54
Original
1248 people have browsed it

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 &#63; event.keyCode : event.which &#63; 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) &#63; -1 : i ;
$('#'+ inputs[i+1].id ).focus()
break;
}
}
}
}
</script>
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template