Clear input fields when button is clicked using javascript

I have a program that dynamically creates input text fields. I want to clear the contents of the boxes by pressing the 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 field values, but don’t know how to make them empty ....

+3
source share
4 answers

use getElementsByTagName (the version of the class is not yet a cross-browser) and set the value to "" for elements with the required 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 the reset input field for the whole form)

+4
source

, <input type="reset" value="clear"/> (HTML). :

var elems = document.getElementsByTagName("input");
var l = elems.length;
for (var i = 0; i < l; ++i){
  elems[i].value="";
}
+4

:

el.value = '';
+3
source

The value elems[i]in your loop will be a string, so you can check its length or the equivalent of an empty string ("). You can also set your value to" "to clear it.

elems[i].value = ""
+3
source

Source: https://habr.com/ru/post/1753157/


All Articles