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.
Solution 2
add an id to your form then just...
document.getElementById("myForm").reset();
![Jacob G](https://i.stack.imgur.com/y3xwk.jpg?s=256&g=1)
Comments
-
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 over 10 yearsThank you. I had tried getElementById but instead of just ".reset()" i had put "form.reset()".
-
Pluto over 10 yearsMight as well put in the confirm() inside the onclick itself instead of making a new function... Just use single quotes for the text.
-
Pluto over 10 yearsMight as well take advantage of features HTML provides you... Give the
<form>
aname="myForm"
attribute, and then you can access it withdocument.forms.myForm.reset()
. -
Barmar over 10 yearsThat's a matter of style. I prefer to keep my
onclick
attributes small.