简体   繁体   中英

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. You should be able to do something like:

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

I'm no jQuery expert, though.

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).

I think

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

Should work with jQuery.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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