python38291
python38291

Reputation: 45

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.

Upvotes: 2

Views: 5045

Answers (5)

Rusca8
Rusca8

Reputation: 602

A simple way to get it working is to get the character before the carret with selectionStart:

input.value[input.selectionStart-1];

Adapting your code:

<input id="myInput" type='text' oninput="validate(this)" />

function validate(input) {
    console.log(input.value[input.selectionStart - 1]);
}

Upvotes: 0

AndrewL64
AndrewL64

Reputation: 16301

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'/>

Upvotes: 4

sachin soni
sachin soni

Reputation: 541

var input = "String"; 
var result = input.charAt(input.length-1);

Output: g

Upvotes: 0

S&#225;ndor Jankovics
S&#225;ndor Jankovics

Reputation: 898

The reason you are getting the whole text is that you give the validate function the whole input value. To check the last input character you can split the text to the last char and examine it. If you want to allow certain characters to be entered you have to check each time this char.

Upvotes: 0

Wojciech Kaczor
Wojciech Kaczor

Reputation: 71

The one simplest solution I can think of is console.log(character[character.length-1])

Upvotes: 0

Related Questions