I'm developing an application in ASP.NET + C# + Javascript and I'm using a barcode scanner to read barcode in labels.
This scanner have a auto "Enter" when finish to read, but in my application, every time I press enter key, the page reload and return to main view.
I have a function to disable the enter key, but I need to use in a specific page like a trigger and when the scanner finish, or the enter is pressed, call the Button_Click event.
This is my function to disable the enter key:
<%--Script Disable Key Enter--%>
<script type="text/javascript">
$(document).ready(function () {
$('input').keypress(function (e) {
var code = null;
code = (e.keyCode ? e.keyCode : e.which);
return (code == 13) ? false : true;
});
});
</script>
<%--end function--%>
Remember, I'm using a scanner to read barcodes and after read, it "press" enter key and I need to use this event "press" to call another function, a Button_Click.
Have a possible duplicate, but the other question don't solve my problem. After tried to use this code:
<script type="text/javascript">
$(function () {
$("#<%=SSCC_barcodeReader.ClientID%>").keypress(function () {
$("#<%=BarCodeReader.ClientID%>").click();
});
});
</script>
<script type="text/javascript">
$(document).on("keypress", 'form', function (e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
});
</script>
The page still submit after press any key of the keyboard. Then I'm developed a solution for my problem too simple.
<script type="text/javascript">
$(function () {
$("#<%=SSCC_barcodeReader.ClientID%>").keypress(function (e) {
var code = e.keyCode || e.which;
if (code == 13) {
setTimeout(function () {
$("#<%=BarCodeReader.ClientID%>").click();
}, 500)
clearTimeout(setTimeout);
}
})
});
</script>
<script type="text/javascript">
$(document).on("keypress", 'form', function (e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
});
</script>
The first part I get the keypress event in my TextBox then I verify if the key pressed is ENTER and execute the .click after 500 miliseconds, because my scanner send a confirmation before the complete typing.
The second part is to prevent to return to initial page.