Search code examples
jqueryasp.netkeypress

How to detect ENTER KEY from a barcode scan in ASPX


I have a textbox in WebForm, and user puts focus on that textbox and scan a barcode. The value scanned from the barcode gets put into the textbox. There is an ENTER KEY at the end of that value scanned. I would like to detect the ENTER KEY, but I dont know how to do it.

here is the code that popups message when a keypress occurs.

<script  type="text/javascript">
    $(document).ready(function () {
        $("#txtProductCode").on("keypress", function () {
            alert("asdasd");
        });
    });
</script> 

I found a tutorial to check the entered value like below

if (e.keyCode == 13) ....

but I dont have the "e" object.... So how can I check the KeyCode on KeyPress


Solution

  • The e is the short var reference for event object which will be passed to event handlers.

    The event object essentially has lot of interesting methods and properties that can be used in the event handlers, like the keyup() function.

    $("#txtProductCode").keyup(function (e) {
        if (e.keyCode == 13) {
            alert("asdasd");
        }
    });
    

    In your case, your are just missing the parameter.

    <script  type="text/javascript">
        $(document).ready(function () {
            $("#txtProductCode").on("keypress", function (e) {
              if (e.keyCode == 13) {
                alert("asdasd");
              }
            });
        });
    </script> 
    

    You can find more information in the .on documentation.