Jquery press enter on the keyboard

  • 2020-03-30 02:55:51
  • OfStack

Next we use Jquery to implement the Enter key to switch the focus, this code passed the test in the common 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, refer to 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> 

Analysis:
$(' input: text: first). The focus ();

When the page initializes, focus is positioned within the first text box

Var $inp = $(' input: text);

Type = the collection of elements of the text box

$inp. Bind (keydown, function (e) {}

Bind the 'keydown' event to the text box collection

Var key = e.w hich;

Take the currently pressed key value like the key value of Enter =13

E.p reventDefault ();


Related articles: