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 added
console.log("jQuery selectionStart:", this.selectionStart); // the position where the character will be inserted
console.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 added
console.log("VANILLA selectionStart:", this.selectionStart); // the position where the character will be inserted
console.log("VANILLA selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="inputJQuery" type="text"/>
<input id="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) {
return true;
} else {
return false;
}
}
}
<input id="input">
Hope this helps! :)
Post a Comment for "OnKeyDown Or KeyPress, Detect The Location Of The Inserted Character"