Search Validation

0

I started yesterday to study JavaScript and I am having difficulty in search validation. I'm following the steps in a book I'm using for the proposed project. I needed to send the search form, that is, when I confirmed the search with the unfilled field the function trigger a Alert with a message and did not proceed with the search. However, Alert is being triggered when refreshing the page. Here's 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 ). Is this normal?

    
asked by anonymous 01.08.2017 / 15:12

1 answer

0

Correction

When you assign a role to an element with " on SomeCase" in the JavaScript code using () at the end of its name, the browser understands that it must be executed immediately, () of the end of the 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 validaBusca() function inside the onsubmit that is inside the form tag like this:

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

And delete the part:

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

# 2

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

You can do this:

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>
    
01.08.2017 / 16:15