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 value will be.
It's important that I use these events. I can't just use onKeyUp, because by then the input will have already changed. I want to prevent it from happening in the first place. I've also tried appending the pressed key character to the end of the string, but that doesn't account for cases where you typed a character in the beginning of the string in the input field.
Any ideas? I've looked for a while and it doesn't seem possible but I figured I'd ask.
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"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With