Hi friends , is it possible to clear all textboxes in HTML by calling a javascript function ?
+6
A:
var fields = document.getElementsByTagName('input'),
length = fields.length;
while (length--) {
if (fields[length].type === 'text') { fields[length].value = ''; }
}
J-P
2009-02-20 12:12:07
This is different/better than "reset" because "reset" would return the text fields to their original page-load values (not necessarily empty) whereas this will clear all the text fields, as the OP wanted.
David Kolar
2009-02-20 14:34:27
+4
A:
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).
acrosman
2009-02-20 12:12:36
+5
A:
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.
Neil Barnwell
2009-02-20 12:14:10
+4
A:
var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
troelskn
2009-02-20 12:16:25
I always use ii, rather than the traditional i, because it's impossible to search-replace for single-letter variables.
troelskn
2009-02-20 13:14:00
@troelskn: That's an interesting way to go about it (using `ii` instead of `i`). I'll keep that in mind. :)
musicfreak
2009-09-12 08:04:55
+1
A:
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 = '';
}
}
splattne
2009-02-20 12:16:27