By default, the system uses the Tab key to switch the focus of page elements. Have you ever thought that the Enter key can also achieve this function and have a good user experience. Next, we use Jquery to implement the Enter key to switch focus. This code has been tested in commonly used browsers IE7, IE8, Firefox 3, Chrome 2 and Safari 4.
The development tool used is Microsoft VS2010+Jquery framework
The implementation steps are as follows
1. First reference the Jquery class library
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
2. Javascript code
<script type="text/javascript">
$(function () {
$('input:text:first').focus();
var $inp = $('input:text');
$inp.bind('keydown', function (e) {
var key = e.which;
if (key == 13) {
e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(":input:text:eq(" + nxtIdx + ")").focus();
}
});
});
</script>
analyze :
$('input:text:first').focus();
When the page is initialized, the focus is positioned in the first text box
var $inp = $('input:text');
Take the type=text box element collection
$inp.bind('keydown', function (e) {}
Bind the 'keydown' event to the textbox collection
var key = e.which;
Get the currently pressed key value, such as Enter key value = 13
e.preventDefault();
You can prevent its default behavior from happening and something else happens. Here we prevent PostBack from happening and switch focus instead. Another similar method is stopPropagation, which prevents js events from bubbling up.