如何清除表格? [英] How to clear a form?
问题描述
例如我有一个这样的表格:
For example I have a form like this:
<form method='post' action='someaction.php' name='myform'>
<input type='text' name='text1'>
<input type='text' name='text2'>
<input type='checkbox' name="check1">Check Me
<textarea rows="2" cols="20" name='textarea1'></textarea>
<select name='select1'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type='reset' value='Reset' name='reset'>
<input type='submit' value='Submit' name='submit'>
</form>
当我按下 Reset
时,它会清空所有字段.但是,如果我使用 URL 参数填充某些字段,然后按 Reset
,它只会清空我在表单重新加载后输入的字段.
When I press Reset
it empties all fields. But if I populate some fields using URL params and then press Reset
, it only empties fields which I enter after form reload.
如果在表单加载时已经填充了某些字段,我如何清空所有字段.
How can I empty all fields whether some fields are already populated at the time of form load.
推荐答案
正如其他人指出的那样,我认为您应该重新考虑空白表单的必要性.但是,如果您真的需要该功能,这是一种方法:
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:
普通 Javascript:
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;
}
请注意,我注释掉了清除 hidden
输入的情况.大多数情况下,这不是必需的.
Note that I commented out the case in which I clear the hidden
inputs. Most of the time, this is not necessary.
为此,您需要从按钮的 onclick
处理程序(或其他方式)调用该函数,例如像这样:
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);">
您可以在 jsFiddle 上测试这一切.
You can test it all here on jsFiddle.
如果你在你的项目中使用 jQuery,你可以用更少的代码来做到这一点(并且不需要更改 HTML):
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.
试试这个这里.
这篇关于如何清除表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!