添加相同类javascript的输入值

时间:2016-07-29 08:22:20

标签: javascript arrays

如何添加同类输入的值。我已经尝试过下面的代码,但似乎没有用。我哪里错了?

SharedPreferences

4 个答案:

答案 0 :(得分:2)

试试这个,使用querySelectorAll,您将获得文档中所有元素的class =“compulsory1”:

window.onload = function(){
var x = document.querySelectorAll(".compulsory1");
var total = 0;
for(var i=0;i<x.length;i++)
{
total+=Number(x[i].value);
}
console.log(total);
}
  <input name="name" class="compulsory1" type="text" value="1" /> 
  <input name="name1" class="compulsory1" type="text" value="2" /> 
  <input name="name2" class="compulsory1" type="text" value="3" /> 

答案 1 :(得分:2)

在你的解决方案中,tdsCompulsory不是一个数组,它只是一些第一个元素(输入)。

var tdsCompulsory = document.getElementsByClassName('compulsory1');
var len = tdsCompulsory.length;
var cData = [];
sum = 0;
for(var i = 0; i < len; i++){
    cData.push(tdsCompulsory[i].value);
    sum += +tdsCompulsory[i].value 
}
alert (sum);
<table id="tableID">
<tr>

<td>   <input name="name" class="compulsory1" type="text" value="1" />  </td>
<td>   <input name="name1" class="compulsory1" type="text" value="2" />  </td>
<td>   <input name="name2" class="compulsory1" type="text" value="3" />  </td>

<td>

答案 2 :(得分:1)

这里

var tdsCompulsory = document.getElementsByClassName('compulsory1')[0].value;

您的tdsCompulsory是一个元素,因为您获得了[0]元素。

将您的代码更改为

var tdsCompulsory = document.getElementsByClassName('compulsory1');

for(var i = 0; i < tdsCompulsory.length; i++){
    if(typeof tdsCompulsory[i].value != undefined){
       cData.push(tdsCompulsory[i].textContent);
    }
}

    console.log(cData);

for(var i in cData){
    sum +=parseInt(cData[i]);
}
alert (sum);

或使用foreach方法

[].foreach.apply(tdsCompulsory, (el) => {
   if(typeof tdsCompulsory[i].value != undefined){
        cData.push(tdsCompulsory[i].value);
     }
});

答案 3 :(得分:1)

您可以使用jQuery编写如下:

   <table id="tableID">
                <tr>
                <td>   <input name="name" class="compulsory1" type="text" value="1" />  </td>
                <td>   <input name="name1" class="compulsory1" type="text" value="2" />  </td>
                <td>   <input name="name2" class="compulsory1" type="text" value="3" />  </td>
                <td>
        </table>
        <input type="Button" value="Show Sum" onclick="sumAll()">


     <script> 
        function sumAll(){
            var values = $('.compulsory1');
            var sum = 0;
            for (var i =0; i<values.length; i++) {
            console.log(values[i]);
            sum += parseInt($(values[i]).val());
        }
        alert(sum);
     }
    </script>

谢谢, 拉维