html 不填写所有字段或按钮获取总和

bejyjqdl  于 2022-12-16  发布在  其他
关注(0)|答案(2)|浏览(143)

我有一个有3个数字输入的表,我想对它们求和,但是由于某种原因没有最终输出,即使我检查了函数和oninput类是否正在运行。

var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
var num3 = document.getElementById("num3");

function add_number() {
  var result = num1 + num2 + num3;
  document.getElementById("total").value = result;
}
<table class="table table-bordered table-hover">
  <tbody>
    <tr>
      <th scope="row">number1</th>
      <td><input type="number" id="num1" name="number1" class="form-control" oninput="add_number()"></td>
    </tr>
    <tr>
      <th scope="row">number2</th>
      <td><input type="number" id="num2" name="number2" class="form-control" oninput="add_number()"></td>
    </tr>
    <tr>
      <th scope="row">number3</th>
      <td><input type="number" id="num3" name="number3" class="form-control" oninput="add_number()"></td>
    </tr>
    <tr>
      <th scope="row">Total</th>
      <td><input type="number" id="total" name="finaltotal" class="form-control"></td>
    </tr>
</table>
bfrts1fy

bfrts1fy1#

首先,需要在add number中添加num1num2num3,以便每次输入一个数字时,此函数都会加载您输入的数字。
其次,你需要调用document.getElementById()的属性.value,这将返回一个字符串,其中包含输入文本字段的值,但是,嘿,这是一个字符串,你需要将其转换为整数,以便能够添加它。
第三步也是最后一步,将每个输入和工作解析为Int

function add_number() {
        var num1 = parseInt(document.getElementById("num1").value);
        var num2 = parseInt(document.getElementById("num2").value);
        var num3 = parseInt(document.getElementById("num3").value);
        var result = num1 + num2 + num3;
        console.log(num1);
        document.getElementById("total").value = result;
      }
yxyvkwin

yxyvkwin2#

使用.value获取输入值,并使用Number()将其转换为数字。

var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
var num3 = document.getElementById("num3");

function add_number() {
  var result = Number(num1.value) + Number(num2.value) + Number(num3.value);
  document.getElementById("total").value = result;
}
<table class="table table-bordered table-hover">
  <tbody>
    <tr>
      <th scope="row">number1</th>
      <td><input type="number" id="num1" name="number1" class="form-control" oninput="add_number()"></td>
    </tr>
    <tr>
      <th scope="row">number2</th>
      <td><input type="number" id="num2" name="number2" class="form-control" oninput="add_number()"></td>
    </tr>
    <tr>
      <th scope="row">number3</th>
      <td><input type="number" id="num3" name="number3" class="form-control" oninput="add_number()"></td>
    </tr>
    <tr>
      <th scope="row">Total</th>
      <td><input type="number" id="total" name="finaltotal" class="form-control"></td>
    </tr>
</table>

相关问题