如何从“表单”中取出2个数字并添加它们以便输出结果

问题描述 投票:0回答:4

我是JavaScript的新手,我真的无法让它完全运行。我有一个带有2个数字的表单和一个运行一个函数的按钮,该函数应该添加2个数字并显示它们,但它只显示为纯文本(例如我提交5和23它会显示为“523” “)。

<html>

  <head>
    <meta charset="UTF-8" />
    <title>My Page</title>
  </head>

  <body>
    <form>
      <label for="num1">First number:</label>
      <input type="number" id="num1" name="num2">
      <br>
      <label for="num2">Second number:</label>
      <input type="number" id="num2" name="num2">
      <button type="button" class="btn" onclick="addNums()">Calculate</button>
    </form>
  </body>
  <script src="main.js"></script>
</html>

JS:

function addNums()
{
    let num1 = document.querySelector("#num1").value;
    let num2 = document.querySelector("#num2").value;
    document.write(num1 + num2);
}
javascript
4个回答
1
投票

它将你的num1和num2变量连接成字符串。你需要使用像Number之类的东西将它转换为数字,如下所示:

let num1 = Number(document.querySelector("#num1").value);
let num2 = Number(document.querySelector("#num2").value);
document.write(num1 + num2);

0
投票

num1和num2的值是string类型,+符号是连接值而不是添加它们,您可以通过使用parseInt函数转换值来解决问题。

这是一个example


0
投票

function addNums()
{
    let num1 = parseInt(document.querySelector("#num1").value);
    let num2 = parseInt(document.querySelector("#num2").value);
    document.write(num1 + num2);
}
<html>

  <head>
    <meta charset="UTF-8" />
    <title>My Page</title>
  </head>

  <body>
    <form>
      <label for="num1">First number:</label>
      <input type="number" id="num1" name="num2">
      <br>
      <label for="num2">Second number:</label>
      <input type="number" id="num2" name="num2">
      <button type="button" class="btn" onclick="addNums()">Calculate</button>
    </form>
  </body>
  <script src="main.js"></script>
</html>

你应该将string转换为int


0
投票

将您的功能更改为:

function addNums() {
  let num1 = document.querySelector("#num1").value;
  let num2 = document.querySelector("#num2").value;
  document.write(+num1 + +num2);
}

另外,如果您计划通过表单发布,请将第一个输入名称num2更改为num1。

© www.soinside.com 2019 - 2024. All rights reserved.