Search code examples
javascripthtmlfunctioncall

run function after the user has entered the 4 first digits in an input field


I have an input field for credit cards and I want to run a function after the user has entered the 4 first digits of the card number in order to indicate the card type.

I want the function to run only one time and then stop.

I tried with timer but I did not like the result because the form was reloading every few seconds. I also don't want to wait until the user stops typing the whole number.


Solution

  • You can simply check it with onkeyup event, like this:

    var testIt = function testIt(num) {
    
      if (num.length === 4) {
        alert("more than 4 characters have been entered");
      }
    }
    Card number: <input type="number" onkeyup="testIt(this.value);" />

    It will only execute if you enter the fourth number.