I've got a form on a page where the user types something in and then a result is returned and displayed on the page. Is it possible for me to have a button that will both, clear the search results and the form simultaneously?
I know that you can use the <input type="reset" value="Reset"/>
button on the form to reset the form and also use the following code, to reload the page.
<input type="button" value="Clear Results" onClick="window.location.reload()">
Is it possible to have the button do both things i.e. clear the search results and reset the form? Can it be done using JavaScript, if so how?
Thanks
Form reset() MethodThe reset() method resets the values of all elements in a form (same as clicking the Reset button). Tip: Use the submit() method to submit the form.
You can easily reset all form values using the HTML button using <input type=”reset”> attribute. Clicking the reset button restores the form to its original state (the default value) before the user started entering values into the fields, selecting radio buttons, checkboxes, etc.
The reset button brings the form back to it's initial, default state. It doesn't necessarily clear the form: if the form was initially blank, it will be cleared.
On a Windows-based computer, pressing the F5 function key or Ctrl + R refreshes a web page on all browsers.
If you want the functionality of both of the snippets you posted, you can simply combine them.
<input type="reset" value="Reset" onClick="window.location.reload()">
I'm a fan of @MikeyHogarth's suggestion since it's called regardless of how the page is refreshed. This is one of those rare times that I find straight javascript to be simpler than jquery so I just wanted to add the code for that.
$(document).ready(function () {
resetForms();
});
function resetForms() {
document.forms['myFormName'].reset();
}
This uses the form name attribute, and if you'd prefer using the form id attribute use this instead:
document.getElementById('myFormId').reset();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With