1

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!

User not found
  • 479
  • 3
  • 15
  • By properly indenting the code and using whitespace instead of stuffing everything together into an unreadable mess, we can clearly see that your JS code is missing the closing brace at the end. If that isn't just a copy and paste error. –  May 04 '21 at 06:12
  • Yes I actually have a `navigator.vibrate` function below so I forgot to copy that. – User not found May 04 '21 at 06:24

3 Answers3

2

You didn't close the last }

document.getElementById('reset').addEventListener('click', clearForm);

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">Reset info</button>

Instead of use onclick function i suggest you to use addEventListener

Good question:

-addEventListener vs onclick

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
2

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

naveen
  • 53,448
  • 46
  • 161
  • 251
1

There was a problem with the id="reset" it was messing with the function reset().

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="resets" onclick="clearForm();">Reset info</button>
User not found
  • 479
  • 3
  • 15