AddEventListener - KeyPress - Javascript - unmodified HTML

0

Of a form HTML without being able to touch it, we depend on programming a .js in Javascript. We have several fields input in which you must control the introduction of correct information (only letters in fields such as name or surname, and only numbers in CP).

How could this code retouched in HTML be transformed into a code without touching the HTML? Let me explain.

First form. Editable HTML + JS:

<input type="text" name="nombre" id="idnombre" size="20" onKeyPress="return soloLetras(event);" onKeyUp="javascript:this.value=this.value.toUpperCase();">
<input type="text" name="apellidos" id="idapellidos" size="40" onKeyPress="return soloLetras(event);">

function soloLetras(e){
    var key = e.keyCode || e.which;
    var tecla = String.fromCharCode(key).toLowerCase();
    var letras = " áéíóúabcdefghijklmnñopqrstuvwxyz";
    var especiales = "8-37-39-46";

    var tecla_especial = false
    for(var i in especiales){
        if(key == especiales[i]){
            tecla_especial = true;
            break;
        }
    }

    if(letras.indexOf(tecla) == -1 && !tecla_especial){
        return false;
    }
}

Second form. HTML NOT editable + JS:

<input type="text" name="nombre" id="idnombre" size="20">
<input type="text" name="apellidos" id="idapellidos" size="40">

Where do I have the error?

window.onload = function(){
    miformulario.nombre.addEventListener("keypress", function(){
        return soloLetras(event);
    }, false);

    miformulario.nombre.addEventListener("keyup", function(){
        this.value = this.value.toUpperCase();
    }, false);

    miformulario.apellidos.addEventListener("keypress", function(){
        return soloLetras(event);
    }, false);
}
    
asked by omaza1990 16.05.2017 в 13:05
source

2 answers

1

You can add events as follows in your funciones.js file by using element.addEventListener() .

This would be the equivalent to the code you have put:

/* Tu función, tal y como la tienes con su parámetro */
function soloLetras(e) {
    var key = e.keyCode || e.which;
    var tecla = String.fromCharCode(key).toLowerCase();
    var letras = " áéíóúabcdefghijklmnñopqrstuvwxyz";
    var especiales = "8-37-39-46";

    var tecla_especial = false
    for(var i in especiales){
        if(key == especiales[i]){
            tecla_especial = true;
            break;
        }
    }
    if(letras.indexOf(tecla) == -1 || tecla_especial){
        /* Evitamos la pulsación */
        e.preventDefault();
    }
}
/* Agrego el evento "onload" a la página para agregar los gestores de
  eventos cuando la página se haya generado */
window.addEventListener("load", function() {
  /* Agrego un gestor de eventos "keypress" para todos los campos de tipo "text" */
  var inputs = document.querySelectorAll('input[type="text"]');
  /* No es posible usar .forEach en todos los navegadores por ser un NodeList */
  for (var i = 0; i < inputs.length ; i++) {
    inputs[i].addEventListener(
      "keypress",
      soloLetras,
      false
    );
  }
  /* Lo mismo para el evento "onkeyup" del campo "nombre" */
  miformulario.nombre.addEventListener(
    "keyup",
    function(){
      if (this.value != this.value.toUpperCase()) {
        var start = this.selectionStart,
          end = this.selectionEnd;
        this.value = this.value.toUpperCase();
        this.setSelectionRange(start, end);
      }
    },
    false
  );
});
<!-- La siguiente línea sólo funciona cuando generes el archivo
  llamado "funciones.js", aquí lo dejo con carácter ilustrativo -->
<script src="funciones.js"></script>
<form name="miformulario" onSubmit="return validar(this)">
  <input type="text" name="nombre" id="idnombre" size="20">
  <input type="text" name="apellidos" id="idapellidos" size="40">
</form>

Keep in mind that in this specification the EventListener does not return anything:

// Introduced in DOM Level 2:
interface EventListener {
  void handleEvent(in Event evt);
};

So you have to use Event.preventDefault() to prevent it from propagate the event and, in this way, cancel the key press.

Edito: Improvement suggested by the author to add the "keypress" event manager to all text type fields. I used document.querySelectorAll() to get the list of items and I iterated through them using a loop for due to the inability to use Array.forEach in certain browsers because it is a NodeList .

    
answered by 16.05.2017 / 14:15
source
1

What you seem to need is to assign event handlers to certain elements by selecting them from DOM .

To do this you can, in this case, select the elements by their attribute name .

Example:

document.querySelector('[name=nombre]').addEventListener('keypress', soloLetras);
document.querySelector('[name=apellidos]').addEventListener('keypress', soloLetras);
    
answered by 16.05.2017 в 13:47