我有一张表格,我希望将完成的数字加在一起。文本和日期输入无需任何操作。我想显示span元素中的数字总数,其中id为" total"。
function myFunction() {
var x = document.getElementById("form");
total = 0;
var i;
for (i = 0; i < x.length ;i++) {
total = total + x.elements[i].value;
}
document.getElementById("demo").innerHTML = total;
}
&#13;
<form id="form">
<tr>
<td><input type="text"></td>
<td><input type="number"></td>
<td><input type="date"></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="number"></td>
<td><input type="date"></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="number"></td>
<td><input type="date"></td>
</tr>
</form>
</table>
</div> <button class="trigger" onclick="myFunction()"> Bereken
studietempo </button>
<div class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<p>Je hebt tot nu toe <span id="total"></span> ECTS behaald.</p>
<p>Je huidige studietempo is:</p>
<p>0 ECTS / maand.</p>
<p>Op basis van dit studietempo heb je 15 maanden nodig voor je P</p>
</div>
</div>
&#13;
三江源!
答案 0 :(得分:1)
我想用id显示span元素中的数字总数 &#34;总&#34;
您正试图将所有值加起来Elements x.elements
并不排除text
和date
,
使用querySelector
和reduce
var x = document.getElementById("form");
var total = Array.from( x.querySelectorAll( "[type='number']" ) )
.reduce( ( a, c ) => a + ( isNaN( c ) ? 0 + c ), 0 );
我想用id显示span元素中的数字总数 &#34;总&#34;
现在显示此总数
document.getElementById("total").innerHTML = total;
答案 1 :(得分:0)
您需要使用此for-loop
:
for (var i = 0; i < x.elements.length; i++) {...}
解析值如下:
total = total + (isNaN(Number(x.elements[i].value)) ? 0 : Number(x.elements[i].value));
每个TD的第一个输入是text
的类型,更改为number
<td><input type="text"></td>
^
function myFunction() {
var x = document.getElementById("form");
var total = 0;
for (var i = 0; i < x.elements.length; i++) {
if (x.elements[i].type === 'number') {
total += (isNaN(Number(x.elements[i].value)) ? 0 : Number(x.elements[i].value));
}
}
document.getElementById("demo").innerHTML = total;
}
&#13;
<table>
<form id="form">
<tr>
<td><input type="number"></td>
<td><input type="number"></td>
<td><input type="date"></td>
</tr>
<tr>
<td><input type="number"></td>
<td><input type="number"></td>
<td><input type="date"></td>
</tr>
<tr>
<td><input type="number"></td>
<td><input type="number"></td>
<td><input type="date"></td>
</tr>
</form>
</table>
<button class="trigger" onclick="myFunction()"> Bereken
studietempo </button>
<div class="modal">
<div class="modal-content">
<!--span class="close-button">×</span>
<p>Je hebt tot nu toe <span id="total"></span> ECTS behaald.</p>
<p>Je huidige studietempo is:</p>
<p>0 ECTS / maand.</p>
<p>Op basis van dit studietempo heb je 15 maanden nodig voor je P</p-->
</div>
</div>
<p>Demo</p>
<span id="demo"></span>
&#13;