前提
inputに数値を入力するとリアルタイムに計算結果(足し算)が反映される仕組みを作りたいと思っています。
inputに数値を入力しても計算結果が0となってしまいます。
実現したいこと
inputに数値を入力すると
html
1<td id="sum-p1"></td>
にリアルタイムで計算結果(足し算)を出す
該当のソースコード
html
1<table> 2 <tbody id="score"> 3 <tr> 4 <th>1</th> 5 <td class="score-p1"><input type="number"></td> 6 </tr> 7 <tr> 8 <th>2</th> 9 <td class="score-p1"><input type="number"></td> 10 </tr> 11 <tr> 12 <th>3</th> 13 <td class="score-p1"><input type="number"></td> 14 </tr> 15 <tr> 16 <th>4</th> 17 <td class="score-p1"><input type="number"></td> 18 </tr> 19 <tr> 20 <th>5</th> 21 <td class="score-p1"><input type="number"></td> 22 </tr> 23 </tbody> 24 <tfoot> 25 <tr> 26 <th>合計</th> 27 <td id="sum-p1"></td> 28 </tr> 29 </tfoot> 30</table>
javascript
1window.onload = function(){ 2// 要素を取得 3const score = document.getElementById('score'); 4const scoreElements = score.querySelectorAll('.score-p1 input'); 5var price = 0; 6 7// 取得した要素を反復処理 8for (let i = 0; i < scoreElements.length; i += 1) { 9 const element = scoreElements[i]; 10 if (!isNaN(element.valueAsNumber)) 11 price += element.valueAsNumber; 12} 13 14score.addEventListener('input', () => { 15 document.getElementById('sum-p1').innerText = price; 16}); 17}

回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2022/12/03 13:20