Function reset in JS does not work

0

The button clears the form but does not perform the rest of the functions

function reset() {
        var form   = document.getElementById("form");
        var nome   = document.form.nome.value;

        var set = confirm("Deseja apagar os dados do formulário?");
        if (set == true) {
            alert('Os campos do formulário foram resetados!');
            document.form.reset();
            document.form.nome.focus();
        }
    }

<button type="button" class="btn btn-dark btn-lg" onclick="reset();">Limpar</button>
    
asked by anonymous 07.11.2018 / 02:10

2 answers

0

You're using the name of a native JavaScript method as your function name . This is generating a kind of conflict. When clicking the button will call the native function reset() of the JS reset the form and not called the function you gave the same name as reset .

  

Try naming functions and variables where you are sure that   are not names of functions or native methods or reserved words of the   language. As the language is in the English language, a good way out   conflicts is to give names in Portuguese.

What you have to do is give the function a different name, it can be Reset (first letter capitalized because JS is case sensitive) or whatever name you want (not reserved by the language). In the example below I changed to resetar .

In addition, since you assigned the form to the variable form , you do not need document , otherwise it will give error. Then you should remove these document .

You can also simplify if with only if(set) instead of if(set == true) . The variable alone in if already indicates that it should be true (such as !set indicates that it should be false ):

function resetar() {
   var form   = document.getElementById("form");
   var nome   = form.nome.value;

   var set = confirm("Deseja apagar os dados do formulário?");
   if (set) {
      alert('Os campos do formulário foram resetados!');
      form.reset();
      form.nome.focus();
   }
}
<form id="form">
   <input type="text" name="nome">
   <button type="button" class="btn btn-dark btn-lg" onclick="resetar();">Limpar</button>
</form>
    
07.11.2018 / 02:32
0

HTML has this native function.

<input type="reset" value="Reset">

If you want to enter a confirmation, you can intercept the reset function as follows:

var form = document.querySelector('form');

form.addEventListener('reset', function(e) {
  if(confirm("Do you really want to reset the form?")) {
    alert('Os campos do formulário foram resetados!');
  } else {
    e.preventDefault(); // Previne que a ação de reset seja executada;
  }
});
<!DOCTYPE html>
<html>
<body>

<form action="#">
  Email: <input type="text" name="email"><br>
  Pin: <input type="text" name="pin" maxlength="4"><br>
  <input type="reset" value="Reset">
  <input type="submit" value="Submit">
</form>

<p>Click on the reset button to reset the form.</p>

</body>
</html>
    
07.11.2018 / 06:49