zik
zik

Reputation: 3095

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

Upvotes: 15

Views: 93411

Answers (5)

Don Don Don
Don Don Don

Reputation: 57

Isn`t it better like this in vanilla javascript?

<button onclick="window.location.href = window.location.href">Reload website and reset forms</button>

Upvotes: 0

rockerest
rockerest

Reputation: 10518

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()">

Upvotes: 20

Saeed Rahimi
Saeed Rahimi

Reputation: 235

you can simply redirect page to current location with this code:

$('[data-command="reset"]').click(function () {    
    window.location.href = window.location.href;
}

<input type="button" value="Clear Results" data-command="reset">

Upvotes: 4

Chaya Cooper
Chaya Cooper

Reputation: 2530

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();

Upvotes: 17

Mikey Hogarth
Mikey Hogarth

Reputation: 4702

using JQuery, do something like this on the page;

$(document).ready(function () {
    resetForms();
});

function resetForms() {
    for (i = 0; i < document.forms.length; i++) {
        document.forms[i].reset();
    }
}

and then just use your second input, forms will auto refresh when the page loads back up.

Upvotes: 6

Related Questions