我想计算2个输入字段并将其显示(打印)到<p>标签

时间:2015-12-11 10:12:23

标签: javascript html

嗨朋友(大师)如果有人帮助我,我会很高兴。谢谢伟大的人。你总是帮忙。任何进一步的提示或解释将不胜感激。

<script>
function cal() {
    var firstNumber = document.getElementById("first").value;
    var secondNumber = document.getElementById("second").value;
    var total = firstNumber + secondNumber;
    document.getElementById("display").innerHTML=total;
}

function ca4l2() {
    var firstNumber = document.getElementById("first").value;
    var secondNumber = document.getElementById("second").value;
    var total = firstNumber + secondNumber;
    document.getElementById("display").innerHTML=total;
}
</script>


    <input type="number" id="first" onKeyPress="cal()"> +
    <input type="number" id="second" onKeyPress="cal2()">
    <p id="display"></p

2 个答案:

答案 0 :(得分:0)

改为此,

> animal <- as.character(map[match(animal, map$find), "replace"])
> animal
[1] "mammal"  "reptile" "mammal"  "bird"    "reptile"

如果数字是小数,那么,

var total = parseInt(firstNumber) + parseInt(secondNumber);

答案 1 :(得分:0)

试试这个。

<强> DEMO

<强> HTML:

<input type="number" id="first"> +
<input type="number" id="second">
<button id="btn">
  Calculate
</button>
<p id="display"></p>

<强> JavaScript的:

var first = document.getElementById('first'),
  second = document.getElementById('second'),
  btn = document.getElementById('btn'),
  display = document.getElementById('display');

btn.addEventListener(
  "click", CalNum, false);

function CalNum() {
  display.innerHTML = parseInt(first.value) + parseInt(second.value);
}
  

根据OP的要求,这是另一个如何计算的例子   数字而不使用按钮来激活该功能。

<强> HTML:

<input type="number" id="first"> +
<input type="number" id="second">
<p id="display"></p>

<强> CSS

#display {
  animation: OpacityBlink 1s linear infinite;
  /*You need to use -webkit- and all other properties for this transition to work on all browsers.*/
}

@keyframes OpacityBlink {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

<强>的JavaScript

var first = document.getElementById('first'),
  second = document.getElementById('second'),
  display = document.getElementById('display');

first.addEventListener(
  "keyup", CalNum, false); //assigns the keyup event listener

second.addEventListener(
  "keyup", CalNum, false); //assigns the keyup event listener

function CalNum() {
  if (first.value === "" || second.value === "") {
    display.innerHTML = "Calculating.."; //if inputs value is empty display this string
  } else {
    display.style.animation = "none"; // stops the css3 animation
    display.innerHTML = parseInt(first.value) + parseInt(second.value); //displays the final result
  }
}

/* Please note that this only work if the user uses his keyboard to type the numbers. The CalNum function only fires if the event detects keyup, otherwise nothing will happen. You can always add another event listener for mouse clicks as well. */