开发者

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 possi开发者_JS百科ble 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


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


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.


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">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜