Skip to content Skip to sidebar Skip to footer

Onkeydown Or Keypress, Detect The Location Of The Inserted Character

I don't know if this is possible (it looks like it's not), but I'm trying to find a way to detect, inside the onKeyDown or onKeyPress event of an HTML input tag, what the resulting

Solution 1:

Here I have 2 versions, one with jQuery and other with JavaScript alone.

$("#inputJQuery").on("keydown", function(ev){
	console.log("jQuery value:", $(this).val()); // this is the value before the key is addedconsole.log("jQuery selectionStart:", this.selectionStart); // the position where the character will be insertedconsole.log("jQuery selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
})

document.querySelector("#inputVanilla").onkeydown = function(ev){
	console.log("VANILLA value:", this.value); // this is the value before the key is addedconsole.log("VANILLA selectionStart:", this.selectionStart); // the position where the character will be insertedconsole.log("VANILLA selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><inputid="inputJQuery"type="text"/><inputid="inputVanilla"type="text"/>

Solution 2:

Simply check for the length of the value on keydown. This also works for deleting characters.

You can also check against this in a conditional that returns false to prevent the user from typing in more than a certain number of characters. Note that you'll probably want to check this against the backspace and delete keys (keyCodes 8 and 46 respectively) so that you're able to delete keys once the maximum length is reached.

var input = document.getElementById('input');
input.onkeydown = function(e) {
  console.log(input.value.length);
  if (input.value.length == 10) {
    if (e.keyCode === 8 || e.keyCode === 46) {
      returntrue;
    } else {
      returnfalse;
    }
  }
}
<inputid="input">

Hope this helps! :)

Post a Comment for "Onkeydown Or Keypress, Detect The Location Of The Inserted Character"