Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to clear a form and reset (reload) the page with one button?

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

like image 276
zik Avatar asked Jul 12 '11 15:07

zik


People also ask

How do I reset a form on page load?

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.

How do I clear a form with a button?

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.

What is the purpose of a reset button in a form?

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.

Which button will refresh the form to enter new values?

On a Windows-based computer, pressing the F5 function key or Ctrl + R refreshes a web page on all browsers.


Video Answer


2 Answers

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()">
like image 190
rockerest Avatar answered Oct 15 '22 06:10

rockerest


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();
like image 44
Chaya Cooper Avatar answered Oct 15 '22 05:10

Chaya Cooper