Run javascript function after the user input 4 digits

时间:2019-01-18 14:39:00

标签: javascript

Here is the simple source code

<input type="text" name="verify" maxlength="4">

Is it possible that do not modify source code to achieve? I found some sample on the internet that need use the onkeyup

var x = function x(num) {
  if (num.length == 4) {
    alert("Test");
  }
}
<input type="text" name="verify" maxlength="4" onkeyup="x(this.value);" />

Thank you.

2 个答案:

答案 0 :(得分:5)

您可以只使用javascript添加事件监听器。

ul#numbers
  li
  = phone_numbers
  button data-url=phone_number_path(phone_number) data-method=:delete data-remote=true Delete
document.querySelector('input[name="verify"]').onkeyup = function() {
  if (this.value.length === 4) alert('test');
}

答案 1 :(得分:0)

这是您的相同代码段(您的相同代码),只是添加了验证功能和相应的调用。

const verificationFunction = (value) => {
  alert("here we are runnning the verification over " + value)
}
var x = function x() {
  var element = document.getElementsByName("verify")[0];
  if (element.value.length >= 4) {
    verificationFunction(element.value)
  }
}
<input type="text" name="verify" maxlength="4" onkeyup="x()" />