Reputation: 163
Hello to everyone i need to get the sum of the numbers but i got only string, so i need get numbers. How i should change it to number? i have tried parseInt and Number but nothing helps
var td = document.getElementsByTagName("td");
var input = document.getElementById("myInput");
for ( var i = 0; i < td.length; i++ ){
td[i].addEventListener("click", activeTd);
}
function activeTd(event){
var result = 0;
for ( var i = 0; i < td.length; i++ ){
event.target.style.color = "red";
}
var btn = document.getElementById("myBtn");
btn.addEventListener("click", activeAll);
function activeAll(){
if( event.target.style.color = "red" ){
result = Number(event.target.innerHTML);
input.value += result;
}
}
}
<table>
<tr>
<td>1</td>
<td>11</td>
<td>8</td>
</tr>
<tr>
<td>54</td>
<td>13</td>
<td>22</td>
</tr>
<tr>
<td>15</td>
<td>23</td>
<td>6</td>
</tr>
</table>
<input type="text" id="myInput">
<button id="myBtn">Start</button>
Upvotes: 0
Views: 104
Reputation: 386520
Your target input.value
is a string any addition returns a string, even if a value is a number. You need to take then value of input.value
, convert it to number, add the value as number and assign it back.
input.value = +input.value + +event.target.innerHTML
var td = document.getElementsByTagName("td");
var input = document.getElementById("myInput");
for (var i = 0; i < td.length; i++) {
td[i].addEventListener("click", activeTd);
}
function activeTd(event) {
var result = 0;
for (var i = 0; i < td.length; i++) {
event.target.style.color = "red";
}
var btn = document.getElementById("myBtn");
btn.addEventListener("click", activeAll);
function activeAll() {
if (event.target.style.color = "red") {
input.value = +input.value + +event.target.innerHTML
}
}
}
<table><tr><td>1</td><td>11</td><td>8</td></tr><tr><td>54</td><td>13</td><td>22</td></tr><tr><td>15</td><td>23</td><td>6</td></tr></table>
<input type="text" id="myInput">
<button id="myBtn">Start</button>
Upvotes: 1
Reputation: 370619
The value
of an input
element is always a string - so when you add that string to another variable, even if that other variable is a number
, cocatenation is what results, instead of addition. Cast the input.value
to a number first:
var td = document.getElementsByTagName("td");
var input = document.getElementById("myInput");
for (var i = 0; i < td.length; i++) {
td[i].addEventListener("click", activeTd);
}
function activeTd(event) {
var result = 0;
for (var i = 0; i < td.length; i++) {
event.target.style.color = "red";
}
var btn = document.getElementById("myBtn");
btn.addEventListener("click", activeAll);
function activeAll() {
if (event.target.style.color = "red") {
input.value = Number(event.target.textContent) + Number(input.value);
}
}
}
<table>
<tr>
<td>1</td>
<td>11</td>
<td>8</td>
</tr>
<tr>
<td>54</td>
<td>13</td>
<td>22</td>
</tr>
<tr>
<td>15</td>
<td>23</td>
<td>6</td>
</tr>
</table>
<input type="text" id="myInput" value="0">
<button id="myBtn">Start</button>
Upvotes: 1