如何使用getElementsByClassName检查输入值,像这样?

时间:2014-12-16 04:05:32

标签: javascript

如何使用getElementsByClassName检查输入值,像这样?

当我加载页面时,我想提醒

HAVE VALUE 3 INPUT 
NOT HAVE VALUE 2 INPUT

我该怎么做?

............................................... .................................................. ...............................................

http://jsfiddle.net/3AaAx/37/

<input type="text" class="xxx" value="111"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="222"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="333"/>


<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){

    // this function for use getElementsByClassName on IE 7 and 8 //

    if (!document.getElementsByClassName) {
      document.getElementsByClassName = function(search) {
        var d = document, elements, pattern, i, results = [];
        if (d.querySelectorAll) { // IE8
          return d.querySelectorAll("." + search);
        }
        if (d.evaluate) { // IE6, IE7
          pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
          elements = d.evaluate(pattern, d, null, 0, null);
          while ((i = elements.iterateNext())) {
            results.push(i);
          }
        } else {
          elements = d.getElementsByTagName("*");
          pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
          for (i = 0; i < elements.length; i++) {
            if ( pattern.test(elements[i].className) ) {
              results.push(elements[i]);
            }
          }
        }
        return results;
      }
    }

    var xxx_var = document.getElementsByClassName('xxx');

    alert(xxx_var.length);
});
</script>

1 个答案:

答案 0 :(得分:1)

在var xxx_var = document.getElementsByClassName('xxx');

之后添加以下代码
 var inputCount=0,nonInputCount=0;
for(var i=0;i<xxx_var.length;i++){
  if(xxx_var[i].value != ""){
      inputCount++;
}else{
     nonInputCount++;
     }
}
alert("Input Count " + inputCount + " , and non input count " +nonInputCount );

如果使用jquery,代码就会更容易。

如果您不理解,请告诉我。

感谢
Raviranjan