I have parcel search input, where you can search parcels with a barcode, you can enter the barcode both with the keyboard and with the scanner. I need to clear the old input value when the user scans a new one.
I work with Javascript and As far as I can see, javascript can’t distinguish between a scanner input and keyboard input, so I use time base. At the moment I don’t have a scanner and I use a phone scanner with the Barcode2win app when I test my script it works well, but when a customer checks out with a scanner it doesn’t work, it just prints the barcode’s only last 4 number.
This is my script
document.addEventListener("DOMContentLoaded", function () {
const input = document.getElementById("searchParcels");
let lastKeyTime = 0;
let inputBuffer = "";
const barcodeThreshold = 50; // Time threshold for detecting barcode scanner input
const typingDelay = 200; // Delay to determine if it's keyboard input
let typingTimer;
function processInput(page = 1) {
let search_string = input.value;
fetch(
`${searchRoute}/search?query=${encodeURIComponent(
search_string
)}&page=${page}`,
{
headers: {
"X-Requested-With": "XMLHttpRequest",
},
}
)
.then((response) => response.text())
.then((data) => {
document.querySelector(".parcels-list-container").innerHTML =
data;
attachPaginationLinks(search_string);
})
.catch((error) => console.error("Error:", error));
}
function clearInput() {
input.value = "";
inputBuffer = "";
}
function attachPaginationLinks(query = "") {
const paginationLinks = document.querySelectorAll(
".parcels-list-container .pagination a"
);
paginationLinks.forEach((link) => {
link.addEventListener("click", function (event) {
event.preventDefault();
const url = new URL(this.href);
const page = url.searchParams.get("page");
processInput(page);
});
});
}
input.addEventListener("keydown", function (e) {
const currentTime = new Date().getTime();
const timeDifference = currentTime - lastKeyTime;
if (timeDifference < barcodeThreshold) {
if (e.key.length === 1) {
inputBuffer += e.key;
}
if (inputBuffer.length > 0) {
clearInput();
input.value = inputBuffer;
inputBuffer = "";
processInput();
}
} else {
clearTimeout(typingTimer);
typingTimer = setTimeout(() => processInput(), typingDelay);
inputBuffer = "";
}
lastKeyTime = currentTime;
});
});