views:

1358

answers:

6

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
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
+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
+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
that's going to catch all inputs, not just text...
annakata
Why is this getting voted up?
J-P
I did say I wasn't an expert. I've edited it - is it better now?
Neil Barnwell
Yep, much better :)
J-P
+4  A: 
var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
  if (elements[ii].type == "text") {
    elements[ii].value = "";
  }
}
troelskn
You hit the "post" button 2 sec earlier than me... :-)
splattne
Just curious, what's with the "ii"?
annakata
why is this downvoted? somebody upset it's not a jQuery solution?
annakata
I think because it wouldn't reset selects, checkboxes, radio buttons, etc.
Tom
I always use ii, rather than the traditional i, because it's impossible to search-replace for single-letter variables.
troelskn
@troelskn: That's an interesting way to go about it (using `ii` instead of `i`). I'll keep that in mind. :)
musicfreak
+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
Scary how similar our solutions are. :)
troelskn
I swear I hit the post button and your answer was shown "2 sec ago", mine "0 sec ago" :-)
splattne
Yeah .. it just goes to show how idiomatic our replies are.
troelskn
+1  A: 

I think

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

Should work with jQuery.

Adones Cunha