Reputation: 233
I am trying to create a function that will clear all of my forms (inputs and selects) on the same page and reload the window(refresh the page) that is global and can be called anywhere in my JavaScript or JQUERY. How do I make it global so that it may be used anywhere?
function resetAndReload () {
$('#myform')[0].reset();
$('#myform1')[0].reset();
$('#myform2')[0].reset();
$('#myform3')[0].reset();
window.location.reload();
}
$(document).ready(function () {
$("#button").click(function(){
resetAndReload();
});
});
Upvotes: 0
Views: 202
Reputation: 17330
With pure Javascript it is as simple as this:
for(var i = 0, f = document.querySelectorAll('form'); i < f.length; i++)
f.item(i).reset()
You could wrap this in a global function:
function resetForms(selector){
for(var i = 0, f = document.querySelectorAll(selector || 'form'); i < f.length; i++) f.item(i).reset()
}
By passing it a selector you could even target specific forms:
resetForms('#myFormWithId');
or
resetForms('.registration form[data-resetable]');
Also, reloading your window is already a global function, being tied to the window.location
object, so why not call that as is? You do not need to reinvent the wheel here.
As @Stryner mentioned in the comments, if you are reloading you can force it to reload a server fetched version of your page by passing the true
bool flag to the reload function as such: window.location.reload(true);
- this should clear your forms as well.
Upvotes: 3