简体   繁体   English

使用 javascript 清除所有 HTML 字段

[英]Clear all HTML fields using javascript

是否可以通过调用 javascript 函数清除 HTML 中的所有文本框?

var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
  if (elements[ii].type == "text") {
    elements[ii].value = "";
  }
}
var fields = document.getElementsByTagName('input'),
    length = fields.length;
while (length--) {
    if (fields[length].type === 'text') { fields[length].value = ''; }
}

While not the simplest solution, look into jQuery.虽然不是最简单的解决方案,但请查看 jQuery。 You should be able to do something like:您应该能够执行以下操作:

$("input[type=text]").val('');

I'm no jQuery expert, though.不过,我不是 jQuery 专家。

This should do the work这应该做的工作

var inputElements = document.getElementsByTagName('input');

for (var i=0; i < inputElements.length; i++) {
    if (inputElements[i].type == 'text') {
        inputElements[i].value = '';
    }
}

If all you fields started blank you can call the form's reset method:如果所有字段都以空白开头,则可以调用表单的重置方法:
document.forms[0].reset() (there are usually more elegant ways to get the form handle depending on your specific case). document.forms[0].reset() (根据您的具体情况,通常有更优雅的方式来获取表单句柄)。

I think我认为

$("input:text").val("");

Should work with jQuery.应该与 jQuery 一起使用。

旧帖子..但是,以 jquery 为例:

$("input[type=text],textarea,input[type=email]").val('');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM