I want to restrict an input text through a regular expression. In the first example I use the attribute onkeyup = “lettersOnly(this)” inside the HTML, as follows:
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username" onkeyup="lettersOnly(this)">
</form>
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value = input.value.replace(regex, "");
}
</script>
As per, injecting the “onkeyup” as HTML attribute is considered a bad practice, I want to get the same result but using addEventListener ('keyup', lettersOnly, false). I researched a lot for this specific situation but no answers. Is it possible? I tried the following:
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username">
<!--No more “onkeyup” attribute.-->
</form>
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value.addEventListener('keyup', lettersOnly(input){
input.value = input.value.replace(regex, "");
}, false)
}
</script>
You are adding the even listener inside the lettersOnly function but that function is never called (at least as far as I can see) so the event listener will never be added. You need to add the event listener to the input outside of the function so that it is added as soon as the script tag is processed.
Also, you don’t add the event listener to the input’s value, you add it directly to the input.
You should directly target the respective DOM element, in this case the input filed(using getElementById() for example and apply the addEventListener() method on it, while providing a keyword for the specific event, you could use “keyup”, or maybe “change” and then you should provide the event handler, the function that would run some action when the particular event is triggered. In your case, you want to access the event object within the handler(handlers receive that object by default, it holds data specific for the event) and retrieve the event target, i.e. the one that prdocuded the event(the input field), get its value and modify it.