键入时检查输入中的重复数据

check repeated data in input while typing

本文关键字:数据 输入 检查      更新时间:2023-09-26

我有一个输入

<input required type="text" id="Editbox1"name="EditboxD" value="00" maxlength="2">

我需要检查用户在输入并显示警报时是否写了一个重复的值,如00或22!

以下是最有效的简写方法

var last;
document.getElementById('Editbox1').addEventListener('keypress',(e)=>last = (last === undefined) ? e.keyCode : (e.keyCode === last) ? alert('repeated data') : e.keyCode);

如果你只寻找2个重复的字符,那么你可以这样做:

var lastKey = '';
$('#Editbox1').on('keyup', function(e) {
  //You probably don't want to check to see if they entered backspace twice. 
  //You could also check for other keys like this for example the ENTER key or the TAB key
  //It might even make more sense to use keyCode ranges depending on your use
  if (e.keyCode === 8 ) {
    return;
  }
  //if the current key and last key were the same
  if (lastKey === String.fromCharCode(e.keyCode)) {
    alert();
  //otherwise store the current key into the lastKey var to be check on the next keypress
  } else {
    lastKey = String.fromCharCode(e.keyCode);
  }
});