views:

40

answers:

4

hi...

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

+2  A: 

You could try setting the value:

el.value = '';
Darin Dimitrov
+2  A: 

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="";
}
Gabriel
+2  A: 

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 = ""
Robusto
+2  A: 

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)

galambalazs