Avoid successive getElementById calls with the same parameter

Asked

Viewed 75 times

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 performed on an element with the same "ID", there is some way to call it only 1 time ?

  • 2

    Why not save the result of getElementById in a variable?

  • 1

    @Pabloalmeida I am totally newb in javascript, it is possible you using the code above, expose a solution via code, pls...

  • @Magichat, tried to use <input id='input_nome_cad' type='text' pattern='^([a-zA-Zà-úÀ-Ú0-9]|-|_|\s)+$' title='Nome inválido' /> and define a css in case the input is invalid: #input_nome_cad:invalid { borderColor: red; outline: red; }?

  • @Tobymosque is pq am avoiding HTML5... Can you help me with this question here (http://answall.com/questions/131579/returnr-div-stilo-anterior-ap%C3%B3s-ter-altered-style-only-with-javascrip) ? See if you can help me with this...

2 answers

2

A simple solution is to create a local variable to your function to store the result and use that 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 often return the modified/requested Jquery object itself, which makes it possible to chaining (chaining) call.

An example (incomplete, but you can have an idea) would be:

$('#input_nome_cad').val('')
    .attr('placeholder', 'Nome inválido')
    .focus()
    .css('border-top-color', '#ff0000');
  • 1

    It’s missing the validation of the regex take a look! if(!filter_nome.test(document.getElementById("input_nome_cad").value)){

  • 1

    Oops. True. Thank you. :)

  • @Pablo Almeida I understood your point of view, but in this case I am calling the variable several times, I seek a solution to minimize calls and apply only the intended actions. Not always what you’re looking for is possible, but I’m going to have another look... Vwl

  • There is no "call variable". There is call method. The method is called only once. I believe you’re trying to optimize where you don’t need to.

  • @Pablo Almeida I understood your point of view, but in this case I am "reusing" the variable , I seek a solution to minimize "reuse" and apply only the intended actions. The question of necessity is personal, I thank you in the same way.

  • 1

    @Magichat Take a look at the edition.

Show 1 more comment

2


Routines can be segmented and used in several 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.