I have tried successfully to add all the cell number in a table. What I want to do is to add on the cell which will be checked (using a check box). I want to do it using JavaScript
我已成功尝试在表格中添加所有单元格编号。我想要做的是添加将要检查的单元格(使用复选框)。我想用JavaScript做到这一点
/here is the code/
/这是代码/
<html>
<head>
</head>
<body>
<form name="addValue">
<table id="countit" border="1px">
<tr>
<td><input type="checkbox" name="choice"/></td>
<td>Some value</td>
<td>Some value</td>
<td class="count-me">12</td>
</tr>
<tr>
<td><input type="checkbox" name="choice"/></td>
<td>Some value</td>
<td>Some value</td>
<td class="count-me">2</td>
</tr>
<tr>
<td><input type="checkbox" name="choice"/></td>
<td>Some value</td>
<td>Some value</td>
<td class="count-me">17</td>
</tr>
</table>
</form>
<script language="javascript" type="text/javascript">
function myFunction()
{
var tds = document.getElementById('countit').getElementsByTagName('td');
var sum = 0;
for(var i = 0; i < tds.length; i ++) {
if(tds[i].className == 'count-me'){
sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
}
}
document.getElementById('countit').innerHTML += '<tr><td>' + sum + '</td><td>total</td></tr>';
}
</script>
<button onclick="myFunction()">Click me</button>
</body>
</html>
2 个解决方案
#1
0
modifiying only the JS you can do something like that
只修改JS你可以做那样的事情
myFunction = function()
{
var tds = document.getElementsByName('choice');
var values = document.getElementsByClassName('count-me');
var sum = 0;
for(var i = 0; i < tds.length; i ++) {
if(tds[i].checked){
sum+= parseInt(values[i].innerHTML);
}
}
document.getElementById('countit').innerHTML += '<tr><td>' + sum + '</td><td>total</td></tr>';
}
https://jsfiddle.net/79yf5to4/
search by name instead of the element td. if you want to search by the element you have to search by the row and after by the td.
按名称搜索而不是元素td。如果你想按元素搜索,你必须按行搜索,然后按照td搜索。
#2
0
Using jQuery
function myFunction(){
var sum = 0;
$('#countit tr input[name=choice]:checked').each(i, elmt){
sum += parseInt($(elmt).closest('tr').find('.count-me').text());
};
}
#1
0
modifiying only the JS you can do something like that
只修改JS你可以做那样的事情
myFunction = function()
{
var tds = document.getElementsByName('choice');
var values = document.getElementsByClassName('count-me');
var sum = 0;
for(var i = 0; i < tds.length; i ++) {
if(tds[i].checked){
sum+= parseInt(values[i].innerHTML);
}
}
document.getElementById('countit').innerHTML += '<tr><td>' + sum + '</td><td>total</td></tr>';
}
https://jsfiddle.net/79yf5to4/
search by name instead of the element td. if you want to search by the element you have to search by the row and after by the td.
按名称搜索而不是元素td。如果你想按元素搜索,你必须按行搜索,然后按照td搜索。
#2
0
Using jQuery
function myFunction(){
var sum = 0;
$('#countit tr input[name=choice]:checked').each(i, elmt){
sum += parseInt($(elmt).closest('tr').find('.count-me').text());
};
}