Question

I have a form with a reset button that clears the whole form, but I want a confirm dialog box to pop up and confirm the user wants to reset.

I have the confirm box working, but how do I make it reset the form when the OK button is pressed?

Below is the code I have so far:

function reset() {
  var r = confirm("Are you sure you want to reset all text?");
  if (r == true) {
    form.reset();
  }
}
<form>
  <p>Full Name</p><br><input name="fname" type="text" placeholder="Full Name"><br>
  <p>Address</p><input name="address" type="text" placeholder="Address"><br>
  <p>Email</p><br><input name="email" type="email" placeholder="Email"><br>
  <input type="submit"> <button onclick="reset()" type="button">Reset</button>
</form>

What am I doing wrong?

Was it helpful?

Solution

Try this:

HTML:

<input type="reset" onclick="return confirm_reset();">

JS:

function confirm_reset() {
    return confirm("Are you sure you want to reset all text?");
}

When the onclick function returns false, it prevents the default action of the reset button.

DEMO

OTHER TIPS

add an id to your form then just...

document.getElementById("myForm").reset();

met form reset

Demo

Use a <button> element of type reset and the standard method preventDefault():

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be....Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

document.querySelector('form').addEventListener('reset', function(event) {
  if (!confirm('Are you sure you want to reset?')) {
    event.preventDefault();
  }
});
body {
  display: flex;
}

fieldset {
  margin: 0 0 16px;
}

[type="reset"] {
  float: right;
}
<form>
  <fieldset>
    <legend>Full Name</legend>
    <input name="name">
  </fieldset>
  <fieldset>
    <legend>Address</legend>
    <input name="address">
  </fieldset>
  <fieldset>
    <legend>Email</legend>
    <input name="email" type="email">
  </fieldset>
  <button type="submit">Submit</button>
  <button type="reset">Reset</button>
</form>

You can use JQuery for this !

HTML:

<input type="reset">

JS - JQuery

$(document).on('click', 'input[type="reset"]', function(e){
  if(confirm("Are you sure you want to reset form data?")){}
  else{
   e.preventDefault();
   window.location="#";
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top