简体   繁体   中英

How to detect if user deleted text in input box

I have the following code:

<!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>

And I tried to do the following:

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 = '';
      }

    }

What I tried to do is to check the length of the input box and if the length is zero it should reset the variable all. But it still doesn't work. Any help will be appreciated. Thanks

Use keyup event and just check the if the value.length is zero

 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 } } 
 <form action="#" id="sampForm"> <input id='charInput' type="text"> </form><br /><br /> 

keypress fires before the value in the textbox is changed. try listening for keyup :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM