如何获取用户输入并将其输出到网页[关闭]

问题描述 投票:-8回答:5

我正在尝试创建一个程序,我要求用户输入两个数字输入,然后在添加到一起时显示这两个数字的值(显示类似1 + 2 = 3),然后显示这两个数字相乘(1 * 2 = 2)。示例输出应如下所示,但基于从网站用户收到的输入:

1 + 2 = 3

1 * 2 = 2

javascript input output
5个回答
0
投票

像这样使用prompt

var number1 = parseInt(prompt("Enter a number"));
var number2 = parseInt(prompt("Enter another number"));

document.write(`${number1} + ${number2} = ${number1 + number2}<br>${number1} * ${number2} = ${number1 * number2}`);

0
投票

您可以使用输入标记来获取输入,使用.innerHTML输出到html

function a() {
  document.getElementById("c").innerHTML = Number(document.getElementById("a").value) + Number(document.getElementById("b").value);
}
<input type="number" id="a" />
<input type="number" id="b" onkeyup="a()" />
<div id="c"></div>

0
投票

试试这个

function submit() {
   let test =document.getElementById("text");
   let sum = parseFloat(document.getElementById("firstNumber").value) +parseFloat(document.getElementById("lastNumber").value);
    let mul = parseFloat(document.getElementById("firstNumber").value)  * parseFloat(document.getElementById("lastNumber").value);
   test.innerHTML = document.getElementById("firstNumber").value + ' + ' +document.getElementById("lastNumber").value + " = " +sum +" </br>";
    test.innerHTML += document.getElementById("firstNumber").value + ' * ' +document.getElementById("lastNumber").value + " = " + mul +"\n";
   return true;
}
  First number:<br>
  <input type="number" id="firstNumber" >
  <br>
  Last number:<br>
  <input type="number" id="lastNumber" >
  <br><br>
  <button onclick="return submit();">click</button>


<div id="text"></div>

0
投票

这是您的编程水平可能更熟悉的另一种方法。在这种情况下,我们有输入字段而不是提示。

<!DOCTYPE html>
<html>
 <head>
  <script>
    function calc(){
    var num1 = document.getElementById("in1").value;
    var num2 = document.getElementById("in2").value;
    document.getElementsByTagName("p")[0].innerHTML = num1 + "+" + num2 + "=" + (parseInt(num1) + parseInt(num2));
  }
  </script>
 </head>
 <body>

  <input id="in1" type="number"/>
  <input id="in2" type="number"/>

  <button onclick="calc()">Calculate</button>
  <p></p>
 </body>
</html>

0
投票

因为没有说明我想假设,你在用户访问页面时要求输入数字,而我通过提示请求收到这些输入...

<script>

function init(){
  var input1 = prompt("Please enter the first Number", "First Number");
  var input2 = prompt("Please enter the second Number", "Second Number");

   if (input1 != null && input2 != null) {

     sum = parseInt(input1) + parseInt(input2); 
     str1 = input1 + " + " + input2 + " = " + sum;

     multi = parseInt(input1) * parseInt(input2);
     str2 = input1 + " * " + input2 + " = " + multi;

     document.getElementById("message").innerHTML = str1 + "<br/>" + str2;

    }else{
       alert('...error message');
    }

   }  //end of function...

</script>


<body onload="init()">
  ......    
  <div id="message"></div>
</body>

这应该工作,如预期的那样......

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