How do you reset a form after OK is clicked in a confirm box?

11,419

Solution 1

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

Solution 2

add an id to your form then just...

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

met form reset

Demo

Share:
11,419
Jacob G
Author by

Jacob G

hello i build stuff goodbye

Updated on June 11, 2022

Comments

  • Jacob G
    Jacob G about 2 years

    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?

  • Jacob G
    Jacob G over 10 years
    Thank you. I had tried getElementById but instead of just ".reset()" i had put "form.reset()".
  • Pluto
    Pluto over 10 years
    Might as well put in the confirm() inside the onclick itself instead of making a new function... Just use single quotes for the text.
  • Pluto
    Pluto over 10 years
    Might as well take advantage of features HTML provides you... Give the <form> a name="myForm" attribute, and then you can access it with document.forms.myForm.reset().
  • Barmar
    Barmar over 10 years
    That's a matter of style. I prefer to keep my onclick attributes small.