I have two input fields productName and quantity, productName field is getting populated using a barcode scanner(don't have access to code), my requirement is to detect as soon as the value gets populated in productName fields so that I can parse the value and populate the second field quantity.
<input type="text" id="productName" name="productName">
<input type="text" id="quantity" name="quantity">
Since I don't have access to code that scans the barcode and populate the productName field, there is one possibility which I think of is repeatedly checking if the field has value or not like below
myVar = setInterval(checkValue, 1000);
function checkValue(){
var productName= document.getElementById("productName");
console.log("running");
if (productName && productName.value) {
document.getElementById("quantity").value=productName.value;
clearInterval(myVar);
}
}
But I am looking for a better approach in vanilla Javascript, is there an alternate solution?
You can use onchange.
Example:
const productNameField = document.querySelector('#productName');
const quantityField = document.querySelector('#quantity');
const populateQuantityField = () => {
quantityField.value = productNameField.value;
}
productNameField.addEventListener('change', populateQuantityField);
Further Reading: