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

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 javascript to have the number extracted and the form validated so that the page is not updated. Please explain me step by step.

    
asked by anonymous 17.06.2018 / 02:50

2 answers

2

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.

    
17.06.2018 / 03:10
1

I recommend that you do the validation in the JavaScript itself because it is safer because in HTML it is possible for the user to remove the validation tag by means of the inspire element, 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><formid="formCadastro">
  <label for="NUMERO">Digite um número</label><br>
  <input type="number" name="num" id="NUMERO"><br>
  <button type="submit">Enviar</button>
 </form>
    
17.06.2018 / 04:05