Avoiding successive calls from getElementById with the same parameter

2

I have the following code:

function valida_form (){

        var filter_nome = /^([a-zA-Zà-úÀ-Ú0-9]|-|_|\s)+$/ ;
        if(!filter_nome.test(document.getElementById("input_nome_cad").value)){
            document.getElementById("input_nome_cad").value='';
            document.getElementById("input_nome_cad").placeholder = "Nome inválido";
            document.getElementById("input_nome_cad").focus();
            document.getElementById("input_nome_cad").style.borderColor = "#ff0000";
            document.getElementById("input_nome_cad").style.outline = "#ff0000";
            return false;
        }
}

In the code there are several interactions made on an element with the same "ID", is there any way to call it just once?

    
asked by anonymous 01.06.2016 / 01:55

2 answers

2

Whether you can segment routines and use across multiple inputs

function valida_nome(value) {
  var filter_nome = /^([a-zA-Zà-úÀ-Ú0-9]|-|_|\s)+$/;
  return filter_nome.test(value);
};

function layout_error(input) {
  input.value = '';
  input.placeholder = "Nome inválido";
  input.focus();
  input.style.borderColor = "#ff0000";
  input.style.outline = "#ff0000";
};

function layout_ok(input) {
  //input.style.borderColor = "#EFEFEF";
  //input.style.outline = "#EFEFEF";
  input.style = null;
};

function valida_form() {
  var campoDeNome = document.getElementById("input_nome_cad");

  if (!valida_nome(campoDeNome.value)) {
    layout_error(campoDeNome)
    return false;
  }
  layout_ok(campoDeNome);
  return true;
};
<form action="" method="post" onSubmit="return false;">
  <input type="text" name="input_nome_cad" id="input_nome_cad" />
  <button type="button" onclick="valida_form()">Enviar</button>
</form>
    
01.06.2016 / 02:22
2

A simple solution is to create a local variable for your function to save the result and use this variable from then on:

function valida_form(){

    var filter_nome = /^([a-zA-Zà-úÀ-Ú0-9]|-|_|\s)+$/ ;
    var campoDeNome = document.getElementById("input_nome_cad");

    if(!filter_nome.test(campoDeNome.value)){
        campoDeNome.value='';
        campoDeNome.placeholder = "Nome inválido";
        campoDeNome.focus();
        campoDeNome.style.borderColor = "#ff0000";
        campoDeNome.style.outline = "#ff0000";
        return false;
    }
}

If you are using JQuery, you can take advantage of the fact that JQuery functions usually return the modified / requested JQuery object itself, which enables chaining ).

An example (incomplete, but one might have an idea) would be:

$('#input_nome_cad').val('')
    .attr('placeholder', 'Nome inválido')
    .focus()
    .css('border-top-color', '#ff0000');
    
01.06.2016 / 02:02