Search code examples
javascriptformsreset

How to create a reset button which asks if you are sure to reset


I would like to create a reset button which confirms the reset it doesn't seem to work.

function clear() {
  if (confirm("Are you sure you want to reset the form?")) {
    document.getElementById("form-main").reset();
  } else {
    alert("You are safe!");
  }
navigator.vibrate([500,500,500,1000,500,500,500]);
}
<form id="form-main"></form>
<button type="button" id="reset" onclick="clear();">Reset info</button>

Can you please tell me where am I going wrong? Thanks!


Solution

  • The problem is that your function name is clear(). It calls the deprecated document.clear()

    console.log(document.clear)

    So, change the function name to something else.

    function clearForm() {
      if (confirm("Are you sure you want to reset the form?")) {
        document.getElementById("form-main").reset();
      } else {
        alert("You are safe!");
      }
    }
    <form id="form-main"><input type="text"></form>
    <button type="button" id="reset" onclick="clearForm();">Reset info</button>

    P.S: Please use addEventListeners rather than using inline event handlers