Search code examples
javascriptinputkeyboard-eventsonkeyup

How to know the last character entered in input - Javascript


Assuming we have the following input:

<input id="myInput" type='text' onkeyup="validate(this.value)" />

function validate(character) {
    console.log(character)
}

The problem is that I only get the overall value of the input. For example, if I write 2, it returns 2 but if I write a 7 it returns 27, when it should return only 7.


Solution

  • Just retrieve the KeyboardEvent property key from the "keyup" event like this:

    //assign the input element to a variable
    let input = document.querySelector("#myInput"); 
    
    //add a keyup listener to the input that will run the function passing the event to the function as an argument
    input.addEventListener("keyup", function(e) {
        console.log(e.key);
    });
    <input id="myInput" type='text'/>

    JSFiddle with above code: https://jsfiddle.net/AndrewL64/n18wqzjm/4/


    But wait, what if I want certain keys to run something else like say, run a different console.log instead?

    Well, you can just add a conditional statement that checks the key property value and compare it with individual keys like this:

    let input = document.querySelector("#myInput");
    
    input.addEventListener("keyup", function(e) {
    	if (e.key === "Delete") {
        //if the DELETE key is pressed, don't run the default console.log but do something else
        console.log("You are trying to add delete key as a character: " + e.key);
      } else if (e.key === "Escape") {
        //if the ESCAPE key is pressed, don't run the default console.log but do something else
      	console.log("You are trying to add escape key as a character: " + e.key);
      } else {
        //run the default console.log
      	console.log(e.key);
      }
    });
    <input id="myInput" type='text'/>