Function reset form in JS does not work

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>
Author: Isac, 2018-11-07

2 answers

You are using as a function name a name of a native JavaScript method . This is generating a kind of conflict. Clicking the button will call the native function reset() of the JS reset the form and not call the function you gave the same name as reset.

Look for naming functions and variables where you are sure that they are not native function names or methods or reserved words of the language. As the language is in the English language, a good output to avoid conflicts is to give names in Portuguese even.

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

In addition, since you have assigned the form to the variable form, you do not need document, otherwise it will give error. Then 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 (just like !set indicates that it should befalse):

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>
 1
Author: Sam, 2018-11-07 01:44:00

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>
 1
Author: Rafael Lopes, 2018-11-07 05:49:16