clear input boxes on button click with javascript
14,978
Solution 1
use getElementsByTagName (the class version is not cross-browser yet) and set the value to "", for the elements with the desired class.
var cname, elems = document.getElementsByTagName("input");
for ( var i = elems.length; i--; ) {
cname = elems[i].className;
if ( cname && cname.indexOf(CLId) > -1 ) {
// empty the input box
elems[i].value = "";
}
}
(or you can use a reset input box for the entire form)
Solution 2
if it is in a form, you can simply use the <input type="reset" value="clear"/>
tag (HTML). Otherwise you will want:
var elems = document.getElementsByTagName("input");
var l = elems.length;
for (var i = 0; i < l; ++i){
elems[i].value="";
}
Solution 3
You could try setting the value:
el.value = '';
Solution 4
The value of elems[i]
in your loop is going to be a string, so you can test its length or its equivalent to the empty string (""). You can also set its value to "" to clear it.
elems[i].value = ""
Author by
coder247
Updated on June 28, 2022Comments
-
coder247 almost 2 years
I've a program which creates text input boxes dynamically. I want to clear the contents of the boxes on the click of clear button.
var elems = document.getElementsByClassName(CLId); var myLength = elems.length; var total = 0; for (var i = 0; i < myLength; ++i) { if(elems[i].value != null && elems[i].value > 0){ var el = elems[i]; } }
I use this to get the values of the boxes, but don't know how to make them empty....