如何检测用户是否在输入框中删除了文本

时间:2017-08-30 08:17:47

标签: javascript html

我有以下代码:

<!DOCTYPE html>
<html>
    <body>
        <!-- When a user clicks a key provide info on the key clicked -->
        <form action="#" id="sampForm">
            <input id='charInput' type="text">
            <p id="keyData">Key Data Here</p>
        </form><br /><br />

    </body>

<script>

    function getChar(event) 
    { 
      // event.which returns the key or mouse button clicked
      if (event.which == null) {
        // Return the char if not a special character
        return String.fromCharCode(event.keyCode); // IE
      } else if (event.which!=0 && event.charCode!=0) {
        return String.fromCharCode(event.which);   // Other Browsers
      } else {
        return null; // Special Key Clicked
      }
    }

    var all = '';

    document.getElementById('charInput').onkeypress = function(event) 
    {
      var char = getChar(event || window.event)
      if (!char) return false; // Special Key Clicked

      // document.getElementById('keyData').innerHTML = char + " was clicked";
      all += char;
      document.getElementById('keyData').innerHTML = all;
      return true;
    }

</script>

我尝试做以下事情:

document.getElementById('charInput').onkeypress = function(event) 
    {
      var char = getChar(event || window.event)
      if (!char) return false; // Special Key Clicked

      // document.getElementById('keyData').innerHTML = char + " was clicked";
      all += char;
      document.getElementById('keyData').innerHTML = all;
      return true;

      if ( ( (document.getElementById('charInput').value).length) == 0 ) 
      {
            all = '';
      }

    }

我尝试做的是检查输入框的长度,如果长度为零,则应重置变量all。 但它仍然无效。任何帮助将不胜感激。感谢

2 个答案:

答案 0 :(得分:5)

使用keyup事件,只检查value.length是否为零

&#13;
&#13;
function getChar(event) {
  // event.which returns the key or mouse button clicked
  // Return the char if not a special character
  if (event.which === null) return String.fromCharCode(event.keyCode); // IE
  else if (event.which !== 0 && event.charCode !== 0) return String.fromCharCode(event.which); // Other Browsers    
  return null; // Special Key Clicked
}



document.getElementById('charInput').onkeyup = function(event) {
  if (this.value.length === 0) {
    alert('Empty');
    // variable resetting here
  }
}
&#13;
<form action="#" id="sampForm">
  <input id='charInput' type="text">
</form><br /><br />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

keypress在文本框中的值更改之前触发。试着听keyup

document.getElementById('charInput').onkeyup = function(event) 
{
      //...
}