Javascript – By Pressing Enter key move to next Textbox in ASP.Net

asp.netjavascriptjquery

I have two textboxes and one Button control…..In first TextBox when press enter key moves to next textbox(Barcode) and when i press enter in barcode textbox it fires the button click event……till that its ok….

But what happening after fireing the Button click even on enter in Barcode Textbox its going back to focus on first textbox………But i want this to stay in same Barcode TextBox to scan more barcodes.

The code is below.

 <script type="text/javascript" 
        src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
    </script>

<Head>
<script type="text/javascript">
        $(function() {
            $('input:text:first').focus();
            var $inp = $('input:text');
            $inp.bind('keydown', function(e) {
                //var key = (e.keyCode ? e.keyCode : e.charCode);
                var key = e.which;
                if (key == 13) {
                    e.preventDefault();
                    var nxtIdx = $inp.index(this) + 1;
                    $(":input:text:eq(" + nxtIdx + ")").focus();
                }                
            });
        });
    </script>

</Head>

Best Answer

You're handling keydown for every textbox.

You need to modify your selector to only handle keydown for the first textbox.

Related Topic