how to read multiple value length in javascript?

I am working on a barcode scanner and currently have a problem where I need the barcode to read 2 different value lengths, currently I have it set to submit the value at 9 length.

          <span>
                <input type="text" id="IC-input" name="IC" onkeyup="autofill(this.value)" placeholder="Enter your IC Number" required maxlength="12">
                <label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
          </span>

        function autofill(value){
        console.log("Autofill:"+value)
        //console.log(9 digits);
        button = document.getElementById("theButton");
        if(value.length == 9){
            console.log('form is ready to submit');
            theButtonIsPressed(value);
        } 
    }

now i need it to read from 12 value as well but it auto submits when the value hits 9 digits. I have tried OR function .

        function autofill(value){
        console.log("Autofill:"+value)
        //console.log(9 digits);
        button = document.getElementById("theButton");
        if(value.length == 12 || value.length == 9){
            console.log('form is ready to submit');
            theButtonIsPressed(value);
        } 
    }

i also tried the Else function

        function autofill(value){
        console.log("Autofill:"+value)
        //console.log(9 digits);
        button = document.getElementById("theButton");
        if(value.length == 12){
            console.log('form is ready to submit');
            theButtonIsPressed(value);
        } 
        else if(value.length == 9){
            theButtonIsPressed(value);
        }
    }

But it would always read the first 9 value and leave the 3 other value unread. Does anyone have a solution for this? Thank you in advance.

Answer

Seems like you are listening to the keypress. Use a timer to cancel it. Basic idea of a debounce method.

var timer;
function autofill(value){
  if (timer) window.clearTimeout(timer);
  if(value.length === 9){
    timer = window.setTimeout( function () {
      processIt(value);
    }, 50);
  } else if(value.length === 12){
    processIt(value);
  } 
}

function processIt(value){
  console.log('here', value);
}

BUT That is a bad solution. Typically you set up the scanner to fire a tab or enter press so you know it is done. I would check to see if that is happening and listen for that instead. You can then just listen for that and you know the scanner is done.

var inp = document.getElementById("barcode");
inp.addEventListener("keydown", function (evt) {
  if (["Tab", "Enter"].includes(evt.key)) {
    evt.preventDefault();
    console.log('scanner is done', evt.target.value);
  }
});
<input type="text" id="barcode" />

Leave a Reply

Your email address will not be published. Required fields are marked *