I have a table and in the table, I have tag to get user input. I want to print or get the value from the table cell. I want to input two number such as 12 and 14 and then print sum value at result id. I don’t want to use the form tag. Is it possible to do this? Thanks.
JavaScript
x
5
1
for(i=0;i<x.length-1;i++)
2
{
3
result=x[i].cellIndex + x[i+1].cellIndex;
4
document.getElementById("result").innerHTML=result;
5
}
JavaScript
1
13
13
1
<!DOCTYPE HTML>
2
<html>
3
4
<body>
5
<table>
6
<tr>
7
<td> <input id="firstnumber" type="number"> </td>
8
<td> <input id="secondNumber" type="number"> </td>
9
</tr>
10
<p id="result"></p>
11
</table>
12
</body>
13
</html>
Advertisement
Answer
Here is a working example
JavaScript
1
9
1
// get the Dom object of the ttwo cells
2
var cell1 = document.querySelector("#firstnumber"),
3
cell2 = document.querySelector("#secondNumber");
4
5
// when the user writes on each of them the result changes
6
cell1.oninput = cell2.oninput = function() {
7
// + before the cell.value only for casting the string to a number
8
document.getElementById("result").innerHTML = +cell1.value + +cell2.value;
9
}
JavaScript
1
13
13
1
<!DOCTYPE HTML>
2
<html>
3
4
<body>
5
<table>
6
<tr>
7
<td> <input id="firstnumber" type="number"> </td>
8
<td> <input id="secondNumber" type="number"> </td>
9
</tr>
10
<p id="result"></p>
11
</table>
12
</body>
13
</html>