is it possible to clear all textboxes in HTML by calling a javascript function ?
-
3<input type="reset" value="No javascript method"/>some– some2009-02-20 12:16:55 +00:00Commented Feb 20, 2009 at 12:16
-
+1 if the comment above were an answerNatrium– Natrium2009-02-20 12:18:13 +00:00Commented Feb 20, 2009 at 12:18
-
I'm curious - why do you need this?Kornel– Kornel2009-02-20 13:06:07 +00:00Commented Feb 20, 2009 at 13:06
Add a comment
|
7 Answers
var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
8 Comments
splattne
You hit the "post" button 2 sec earlier than me... :-)
annakata
Just curious, what's with the "ii"?
annakata
why is this downvoted? somebody upset it's not a jQuery solution?
troelskn
I always use ii, rather than the traditional i, because it's impossible to search-replace for single-letter variables.
Sasha Chedygov
@troelskn: That's an interesting way to go about it (using
ii instead of i). I'll keep that in mind. :) |
var fields = document.getElementsByTagName('input'),
length = fields.length;
while (length--) {
if (fields[length].type === 'text') { fields[length].value = ''; }
}
1 Comment
David Kolar
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.
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 = '';
}
}
5 Comments
troelskn
Scary how similar our solutions are. :)
splattne
I swear I hit the post button and your answer was shown "2 sec ago", mine "0 sec ago" :-)
ARK
my my, 11 years later, your reputations are still similar except that @troelskn has been a few seconds ahead at a few answers :D
splattne
@ARK That's life! :-)
troelskn
There's some sort of lesson to be derived from this, I'm sure.
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.
1 Comment
Neil Barnwell
I did say I wasn't an expert. I've edited it - is it better now?