Search code examples
javascripthtmladdeventlistenerkeyuponkeyup

How could I get the same result using “addEventListener” ('keyup', function), instead of using “onkeyup” as HTML attribute?


I found this original code. My concern is the validation of the regular expression. You can‘t type numbers because of the function:

<form>
<label for="username">Chosse a Username:</label>
<input type="text" name="username" id="username1" onkeyup="lettersOnly(this)">
</form>

<script>
function lettersOnly(input){
            var regex = /[^a-z]/gi;
            input.value = input.value.replace(regex, "");
}
</script>

As per I read, those events like onkeyup should not be placed like an attribute in the HTML, so I found, after longer hours, another solution WITHOUT the onkeyup attribute, as follows:

<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="texto1">
</form>

<script>
let user = document.getElementById('texto1');
            user.onkeyup = function() {
            var regex = /[^a-z]/gi;
            user.value = user.value.replace(regex, "");
           }
</script>

However, I don‘t really find accurate information if the ON-prefix-events like ONkeyup are still good standards. Is there a way I can get the same effect you get in these two examples but using the addEventListener? I tried the following code with lots of variants but nothing. What can you suggest me?

<form>
<label for="username">Chosse a Username:</label>
<input type="text" name="username" id="username2">
</form>

<script>
function lettersOnly(input){
            var regex = /[^a-z]/gi;
            input.value = input.value.replace(regex, "");
        }
            input.value.addEventListener('keyup', lettersOnly);
</script>

What Am I doing wrong in the last example?


Solution

  • function get_ml(){
        alert('in');    
    }
    
    var el = document.getElementById('ta_in'); 
    
    if (typeof el.addEventListener != "undefined") {
        el.addEventListener("keyup", function(evt) {
            get_ml();
        }, false);
    } else if (typeof el.attachEvent != "undefined") { //incase you support IE8
        el.attachEvent("onkeyup", function(evt) {
            get_ml();
        });
    }
    <textarea id="ta_in" rows="7" cols="42" onkeyup="get_ml()"></textarea>