I have a need to enforce barcode scanner entry into a text field on a web page form, I have to block keyboard or paste entry. This is for use in a manufacturing environment where individual users have their own bar coded card they carry about, they are not allowed to book other peoples work, that would be cheating! The code they scan is their employee number which is always 4 characters long. The barcode scanners are USB and behave as a keyboard entering each individual character in turn.
The code I came up with detects the time it takes between character 1 and 4. If it is below 10 milliseconds then the code was barcode scanned, if it is was longer it was keyboard entered. If the code is pasted then the field is never 1 character long so the timer variable is not set and the time is again longer than 10 milliseconds.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script>
var startTime = new Date().getTime();
function barcodeScanCheck(){
var input = document.getElementById("barcode").value;
if(input.length == 1){
startTime = new Date().getTime();
}
else if(input.length == 4){
var elapsedTime = new Date().getTime() - startTime;
if(elapsedTime < 10){
alert("Barcode");
}
else{
document.getElementById("barcode").value = "";
alert("Keyboard");
}
}
}
</script>
</head>
<body>
<form action="input.html" method="get">
<input id="barcode" name="barcode" type="text" onInput="barcodeScanCheck()">
<input name="submit" type="submit">
</form>
</body>
</html>