Hi friends , is it possible to clear all textboxes in HTML by calling a javascript function ?
From stackoverflow
-
var fields = document.getElementsByTagName('input'), length = fields.length; while (length--) { if (fields[length].type === 'text') { fields[length].value = ''; } }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. -
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). -
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.
annakata : that's going to catch all inputs, not just text...J-P : Why is this getting voted up?Neil Barnwell : I did say I wasn't an expert. I've edited it - is it better now?J-P : Yep, much better :) -
var elements = document.getElementsByTagName("input"); for (var ii=0; ii < elements.length; ii++) { if (elements[ii].type == "text") { elements[ii].value = ""; } }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?Tom : I think because it wouldn't reset selects, checkboxes, radio buttons, etc.troelskn : I always use ii, rather than the traditional i, because it's impossible to search-replace for single-letter variables.musicfreak : @troelskn: That's an interesting way to go about it (using `ii` instead of `i`). I'll keep that in mind. :) -
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 = ''; } }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" :-)troelskn : Yeah .. it just goes to show how idiomatic our replies are. -
I think
$("input:text").val("");Should work with jQuery.
0 comments:
Post a Comment