Search validation

Asked

Viewed 55 times

0

I started studying yesterday JavaScript and I’m having a hard time with the search validation. I am following the steps of a book that I am using for the proposed project. Needed to send the search form, IE, when confirming the search with the field unfilled the function trigger a Alert with a message and did not proceed with the search. However, the Alert is being fired when refreshing the page. Follow the code photo.

function validaBusca() {
if(document.querySelector('#q').value == ''){
    alert('Campo de busca vazio, por favor preencha o campo!');
        return false;
}
}
//Fazendo a associação da função com o evento
document.querySelector('#form-busca').onsubmit = validaBusca();

The Value and onsubmit are not in the autocomplete of IDE (WebStorm). This is normal?

1 answer

0

Correction

When you assign a function to an element by "onSomething" in the code JavaScript using () at the end of her name, the browser understands that it should be run immediately if it removes () end of function name your code will work.

function validaBusca() {
  if(document.querySelector('#q').value == ''){
    alert('Campo de busca vazio, por favor preencha o campo!');
    return false;
  }
}

//Fazendo a associação da função com o evento
busca = document.querySelector('#form-busca').onsubmit = validaBusca;
<form id="form-busca">
  <input id="q" type="text">
  <input type="submit">
</form>

Other ways

#1

You can put the function validaBusca() within the onsubmit that sits within the tag form in this way:

<form id="form-busca" onsubmit="validaBusca()">
  <input id="q" type="text">
  <input type="submit">
</form>

And erase the part:

document.querySelector('#form-busca').onsubmit = validaBusca();

#2

Another way to assign an event to a particular element is through the function addEventListener("evento", "função ou bloco de código"), the event you need is the "submit" that is, it must be triggered when the form is submitted.

You can do it this way:

function validaBusca() {
  if(document.querySelector('#q').value == ''){
    alert('Campo de busca vazio, por favor preencha o campo!');
    return false;
  }
}

//Fazendo a associação da função com o evento
busca = document.querySelector('#form-busca');

busca.addEventListener('submit', validaBusca);
<form id="form-busca">
    <input id="q" type="text">
    <input type="submit">
</form>

  • 1

    Laércio, as informed by the author of the question. He started learning Javascript yesterday. I believe that a better explanation of the answer would be of great help to him. It may be that he does not know what it is addEventListener or even how to call the method directly from HTML.

  • @Bsalvo, understood, I’ll explain.

Browser other questions tagged

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