clear input boxes on button click with javascript
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.getElementsByClassN开发者_高级运维ame(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....
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)
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="";
}
You could try setting the value:
el.value = '';
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 = ""
精彩评论