Put the required
attribute that when submitting the HTML will require the field to be filled. To cancel the submit event, use preventDefault();
, so the form will not be sent and the page will not be reloaded.
For this, you must create a function that receives the form's submit event. You can get the form with document.querySelector("form")
and detect the submit with onsubmit
:
document.querySelector("form").onsubmit = function(e){
// o "e" recebe o evento submit.
// Em vez de "e", você pode usar outra letra ou palavra,
// como "event", "x", "y", "evento", "ev" etc..
// Eu uso "e" por costume. Cada programador tem seus costumes
// em criar nomes de variáveis
e.preventDefault();
console.log("Formulário ok!");
}
<form><label for="NUMERO">Digite um número</label>
<input type="number" name="num" id="NUMERO" min="0" max="100" required>
<button type="submit">Enviar</button>
</form>
The querySelector
selects the element that you specify in the selector. In the case above, I have picked up the form
element, which is the form.
Calling a non-anonymous function:
document.querySelector("form").onsubmit = f;
function f(){
console.log("Formulário ok!");
return false;
}
<form><label for="NUMERO">Digite um número</label>
<input type="number" name="num" id="NUMERO" min="0" max="100" required>
<button type="submit">Enviar</button>
</form>
The return false;
will also cancel the submission of the form.