How to clear a form?
Solution 1:
As others pointed out, I think you should reconsider the need to blank the form. But, if you really need that functionality, this is one way to do it:
Plain Javascript:
function resetForm(form) {
// clearing inputs
var inputs = form.getElementsByTagName('input');
for (var i = 0; i<inputs.length; i++) {
switch (inputs[i].type) {
// case 'hidden':
case 'text':
inputs[i].value = '';
break;
case 'radio':
case 'checkbox':
inputs[i].checked = false;
}
}
// clearing selects
var selects = form.getElementsByTagName('select');
for (var i = 0; i<selects.length; i++)
selects[i].selectedIndex = 0;
// clearing textarea
var text= form.getElementsByTagName('textarea');
for (var i = 0; i<text.length; i++)
text[i].innerHTML= '';
return false;
}
Note that I commented out the case in which I clear the hidden
inputs. Most of the time, this is not necessary.
For this to work, you need to call the function from the onclick
handler of a button (or some other way), e.g. like this:
<input type='reset' value='Reset' name='reset' onclick="return resetForm(this.form);">
You can test it all here on jsFiddle.
If you use jQuery in your project, you can do this with much less code (and no need to change the HTML):
jQuery(function($) { // onDomReady
// reset handler that clears the form
$('form[name="myform"] input:reset').click(function () {
$('form[name="myform"]')
.find(':radio, :checkbox').removeAttr('checked').end()
.find('textarea, :text, select').val('')
return false;
});
});
Also, note that I do not clear the values of hidden inputs, check-boxes and radio buttons.
Play with this here.
Solution 2:
In jquery simply you can use,
$("#yourFormId").trigger('reset');
Solution 3:
You will have to clear them all through javascript (or clear it out server side).
The reset
button will only reset form elements to their initial value - if this was a specific value, that's what it will be reset to.
Solution 4:
The easiest way to clear a form is by using the HTML tag
<input type="reset" value="Reset">
Example:
<form>
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Reset</td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
</form>
Solution 5:
If you're using jQuery, the code is much simpler:
$('#my-form').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
You can also remove the :hidden from the .not selector if you want to clear hidden fields as well.