Reputation: 5482
What I want is NOT to emulate a key press event in javascript, but get the value of a string after a key press.
To clarify; given a text input, I want to see what the value of my text input would be if the user pressed a certain key.
i.e, I want the following function.
function getStringValueAfterKeyPress(string, cursorPosition, keyCode) {
// returns string value after key press with provided code on provided cursor position
}
getStringValueAfterKeyPress('test', 4, 8) // returns 'tes' (8 is keycode of backspace)
getStringValueAfterKeyPress('test', 4, 37) // returns 'test' (37 is keycode of left arrow, hence string value has not changed)
getStringValueAfterKeyPress('test', 4, 49) // returns 'test1' (49 is keycode of '1')
And so on. Is there a simple way of doing this?
P.S my use case will be to use this method on an afterKeyDown event, get the value of my input element after this key press using this method, and if it does not match a certain regex prevent the action.
Upvotes: 0
Views: 2199
Reputation: 26143
You can validate input as it happens by handling the input
event which is triggered every time there is a change in an input field, including keypresses, copy/paste, drag & drop etc..
Here's an example of validating a name input field that doesn't allow numbers...
// our validation function to stop numbers being entered
function noNumbersAllowed() {
this.value = this.value.replace(/\d/g, "");
}
// keep a reference to the element, so we don't have to search the DOM repeatedly
var nameInput = document.getElementById("name");
// create an input event listener that removes all numbers
nameInput.addEventListener("input", noNumbersAllowed);
// set focus because we're nice like that
nameInput.focus();
<input id="name" type="text" placeholder="Enter name (no numbers)"/>
You can have multiple types of validation functions (if you need them) and assign them to whatever inputs require validation.
Upvotes: 1