Place the attribute required
that when doing Submit the HTML will require the field to be populated. To cancel the Submit event, use preventDefault();
, with this the form will not be sent and the page will not be reloaded.
To do this, you must create a function that receives the Submit event from the form. You can take the form with document.querySelector("form")
and detect 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 you specify in the selector. In the above case, I took the element form
, which is the form.
Calling a non-announced 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 sending the form.
I would like in the "Document.querySelector("form"). onsubmit = Function(e){" , instead of "Function(e){.. }" was a function I called, e.g.: "var 2 = Ok(e); Function Ok(e){...code...}"
– Pedro
@Pedro There already escapes the scope of the question. There are ways to do what you want. Give a search or you can ask another question on the site with this new subject.
– Sam
@dvd Last question, has how I do this with addeventlistener ?
– Pedro
has yes:
document.querySelector("form").addEventListener("submit", function(e){ código });
– Sam
@dvd Ah, actually, I think I expressed myself badly in the penultimate comment, I wanted to use instead of an anonymous function, a defined function, but I can’t
– Pedro
Ahh, now it worked. Thank you for helping and it was bad to bother!
– Pedro
I only got it from . onsubmit, but okay]
– Pedro
@Pedro No way to cancel the event with addeventlistener calling an external function.
– Sam
Pedro, be sure to mark in the reply. This is part of the site is important.
– Sam