javascript – Convert to uppercase the keys that are being pressed from any input

Question:

I would like the keys to be converted to uppercase as you type, taking into account that it can be done with any input in the form, that is, that the formula is general.

I have the following:

function mayus(e) {

    var tecla=e.value;
    var tecla2=tecla.toUpperCase();
    
    alert(tecla2);
}
<input type="text" onkeypress="mayus(this);">

Answer:

Instead of using onKeyPress , I recommend that you use onKeyUp , it acts, when you stop pressing the key.

So the only thing we do is, using the toUpperCase() function we will convert the whole chain in general, and it will give the effect that it is done one by one, since in each event of the onKeyUp() the function will be executed.

I mean, it is not necessary to capitalize letter by letter.

Likewise, you can replicate the function in other <input type='text'> and it will work the same, so there is no problem that it is general.

function mayus(e) {
    e.value = e.value.toUpperCase();
}
<input type="text" onkeyup="mayus(this);">
<input type="text" onkeyup="mayus(this);">

Another way to solve it would be like this:

When creating the <input type='text'> , you assign an id to each one, and later you can apply this formula.

<input type="text" id="campo" onKeyUp="document.getElementById(this.id).value=document.getElementById(this.id).value.toUpperCase()">
Scroll to Top