Use Javascript to Overwrite the ‘Enter Keys’ Default Action

or in other words, ‘Making the Enter Key Your Bitch’.

For my most recent project I have been tasked with incorporating bar code scanners into my ASP.NET / C# application. Much easier said than done, especially when almost every bar code scanner comes pre-programmed to press the ‘Enter Key’ after each successful scan. This becomes a real pain in a details view when you need additional information after the scan and the damn form keeps getting submitted.

With the help of a friend, we came up with a method to not only stop the default action of the Enter Key, but also make the cursor go where I wanted it to go next.

Here I have a simple web form asking the user for a Part and Quantity (app is for inventory purposes). The session ID is calculated automagically, so the cursor is in the Part field on page load.

Image

When the user scans the bar code, we want the cursor to move down to Quantity, not click the Submit button.

First thing we do is add the script source to our header. In my case, this is on my Master page.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

Next, we add this little ditty into our ASP.NET page.

<script type="text/javascript">
     $(document).ready(function ()
        {
        $('[id$=TextBox2]').keydown(function (e)
           {
           var code = (e.keyCode ? e.keyCode : e.which);
           if (code === 13)
             {
             // alert("javascript works");
             e.preventDefault();
             $('[id$=TextBox3]').focus();
             }
           });
        });
</script>

A few notes regarding this code: I sometimes use alerts in my JavaScript to check if its working. To test this on your own page, remove the ‘//’ in front of ‘// alert(“javascript works”);’ and you should see a popup box. Otherwise, this line is not needed in your final code. Also, the page I created is sent an ‘id’ through the URL. If you page doesn’t have that, you can remove the ‘id$=’ from the references to your text boxes.

Once you have the code in your page, the ‘$(document).ready(function ()’ will make sure your JavaScript loads with your page. Then its, ‘Wham bam, thank you ma’am!’ The Enter Key is now stopped from pressing the ‘Submit’ button until I say “Go for it, Mr. Enter Key”.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s