简体   繁体   English

应该对来自用户输入的 2 个数字进行乘法和除法的程序

[英]Program that is supposed to multiply & divide 2 numbers coming from user input

I converted both values coming from the user's input to numbers as you can see in my code, however, when I click the button to conduct the operation it returns NaN.正如您在我的代码中看到的那样,我将来自用户输入的两个值都转换为数字,但是,当我单击按钮执行操作时,它返回 NaN。

Here is my HTML:这是我的 HTML:

<form id="#form">
  <p>1st Number: <input id="number1"></p>
  <p>2st Number: <input id="number2"></p>
  <button onclick="multiply()">Multiply</button>
   <button onclick="divide()">Divide</button>
  <br>
  <p id="result">The Result Is:</p>
</form>

and here is my JavaScript:这是我的 JavaScript:

const num1 = Number(document.getElementById("number1").value);
const num2 = Number(document.getElementById("number2").value);

  const multiply = function (num1, num2) {
      const result1 = num1 * num2;
    document.getElementById("result").innerHTML = result1;
  }
  
   const divide = function (num1, num2) {
    const result2 = num1 / num2;
       document.getElementById("result").innerHTML = result2;
  }

Here's one method with jQuery这是 jQuery 的一种方法

  <p>1st Number: <input id="number1"></p>
  <p>2st Number: <input id="number2"></p>
  <button id="multiply">Multiply</button>
  <button id="divide">Divide</button>
  <br>
  <p>The Result Is: <span id="result"></span></p>

JS JS

$( document ).ready(function() {
    
  $('button').click(function() {
    let choice = this.id;
    let n1 = $('#number1').val();
    let n2 = $('#number2').val();
    let result = 0;
    if(n1 != 0 && n2 != 0){
        if(choice == "multiply"){
          result = n1*n2;
        }else{
          result = n1/n2;
        };
        $('#result').html(result);
    }else{
      $('#result').html("Input empty");
    }
  });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM