15

is it possible to clear all textboxes in HTML by calling a javascript function ?

3
  • 3
    <input type="reset" value="No javascript method"/> Commented Feb 20, 2009 at 12:16
  • +1 if the comment above were an answer Commented Feb 20, 2009 at 12:18
  • I'm curious - why do you need this? Commented Feb 20, 2009 at 13:06

7 Answers 7

39
var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
  if (elements[ii].type == "text") {
    elements[ii].value = "";
  }
}
Sign up to request clarification or add additional context in comments.

8 Comments

You hit the "post" button 2 sec earlier than me... :-)
Just curious, what's with the "ii"?
why is this downvoted? somebody upset it's not a jQuery solution?
I always use ii, rather than the traditional i, because it's impossible to search-replace for single-letter variables.
@troelskn: That's an interesting way to go about it (using ii instead of i). I'll keep that in mind. :)
|
9
var fields = document.getElementsByTagName('input'),
    length = fields.length;
while (length--) {
    if (fields[length].type === 'text') { fields[length].value = ''; }
}

1 Comment

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

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

Scary how similar our solutions are. :)
I swear I hit the post button and your answer was shown "2 sec ago", mine "0 sec ago" :-)
my my, 11 years later, your reputations are still similar except that @troelskn has been a few seconds ahead at a few answers :D
@ARK That's life! :-)
There's some sort of lesson to be derived from this, I'm sure.
8

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

Comments

8

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

I did say I wasn't an expert. I've edited it - is it better now?
6

I think

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

Should work with jQuery.

Comments

1

Old post..but, with jquery for example:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.