How can I extract values from a Javascript input, but using HTML validation

Asked

Viewed 89 times

2

 <form><label for="NUMERO">Digite um número</label>
 <input type="number" name="num" id="NUMERO" min="0" max="100">
 <button type="submit">Enviar</button>
 </form>

I would like in javascript the number was extracted and the form validated, so that the page is not updated. Please explain step by step

2 answers

1

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...}"

  • 1

    @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.

  • @dvd Last question, has how I do this with addeventlistener ?

  • has yes: document.querySelector("form").addEventListener("submit", function(e){ código });

  • @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

  • 1

    Ahh, now it worked. Thank you for helping and it was bad to bother!

  • I only got it from . onsubmit, but okay]

  • @Pedro No way to cancel the event with addeventlistener calling an external function.

  • Pedro, be sure to mark in the reply. This is part of the site is important.

Show 4 more comments

1

I recommend that you validate the Javascript itself because it is safer, because in HTML it is possible for the user to remove the validation tag through the element inspencionar, being as follows:

$(document).ready(function(){
  $("#formCadastro").on("submit", function(event) {
    var numero = $("#NUMERO").val();
    if(numero != ''){
    	if(numero >= 0 && numero <= 100){
        //realiza action do form
        return true;
      }
    }
    //não execute action do form
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formCadastro">
  <label for="NUMERO">Digite um número</label><br>
  <input type="number" name="num" id="NUMERO"><br>
  <button type="submit">Enviar</button>
 </form>

  • To remove the validation of js is also not too complicated...

  • "validate in Javascript itself for being more secure" - in fact, the safest even is validated on the server: https://answall.com/q/13298

  • I meant it’s better than pure HTML..

Browser other questions tagged

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