I have a field in a form, the field is called DNI , where I want to enter 8 numbers and a letter . The letter which we put automatically converts it to uppercase using the toUpperCase() method.
The problem I have is that any onkey event (onkeypress, onkeyup, onkeydown) doesn't work for me directly, it needs one more character to "convert" the previous letter. It does not work directly on the entered letter.
.js file
$(document).on('ready',function(){
//Convertimos la letra del DNI en mayúscula en tiempo real con el evento onkeyup "toUpperCase()".
$('#dni').on('keydown', letra_DNI);
});
//Función que convierte la tecla del DNI en mayúscula.
function letra_DNI(e){
this.value = this.value.toUpperCase();
}
.html file:
<input type="text" name="dni" id="dni" placeholder="DNI" maxlength="9" tabindex="4" class="input-2" onkeypress="return soloLetrasNumeros(event);">
A solution can be:
in the event
keypress
in which the character has not yet been included in the input, you check if the typed character is validin the event
keyup
where the character has already been included in the input you change any lowercase character to the corresponding uppercase oneHere is an example.
In the event
keypress
, it is verified that the character is a number and that 8 has not yet been entered, or that it is a letter and that 8 digits have already been entered. If not, reject the input.In the event it
keyup
replaces any lowercase letter entered with the corresponding uppercase one.If you use the keyboard event keyup you will not have problems.