使用 Javascript 将字段输入除以 12

divide field input by 12 using Javascript

我需要获取用户在输入字段中键入的数字,并在该字段下方显示该数字将除以 12 的结果。这需要是纯 JS,而不是 Jquery。

理想情况下它也需要四舍五入,所以 1083.3333333333333 将变成 1083

谢谢

有时候感觉就像在做别人的作业。无论如何,这可能会对您有所帮助。尽管这是非常基础的 javascript 和 html,您可以很容易地在网上或在您的课程书中查找 :)

剧透:前方未经测试的代码

html

<input id="number" type="text">
<div id="output"></div>

js

//obtain reference to number html element
var number = document.getElementById('number');

//obtain reference to output html element
var output = document.getElementById('output');

//what you want to divide to
var division = 12; // can't be 0, or the world will explode

//add an eventlistener to the change event on the number element
number.addEventListener('keyup', function(e) {

  //get the value from the input
  var val = parseFloat(number.value);

  //check if it is a nan
  if(!isNaN(val)) {

     //round it to 0 digits
     output.innerHTML = (val / division).toFixed(0) + "";
  } else {
     output.innerHTML = 'that\'s not a number!';
  }
});

JsFiddle

<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<script type="text/javascript">
    function updatesum()
 {
        document.input.total.value = Math.ceil(document.input.input1.value / 80) * Math.ceil(document.input.input2.value / 80) * Math.ceil(document.input.input3.value / 80);
        return false;
    }
</script>
<body>
    <form name="input" action="#" method="get" onsubmit="return false;">
        Calculator<br>
        Value1:<input type="text" name="input1" value=""><br>
        Value2:<input type="text" name="input2" value="2"><br>
        Value3:<input type="text" name="input3" value=""><br>
        Costs:<input type="text" name="total" value="">
        <input type="button" value="Calculate" onclick="updatesum()">
   </form>
</body>
</html>

试试这个

var userInput = document.getElementById('number');
userInput.addEventListener('keyup', function(e) {
    if (isNumeric(this.value) == true) {
      var divide = Math.round(this.value / 12);
      document.getElementById('result').innerHTML = divide;
    } else {
      document.getElementById('result').innerHTML = 'please enter number';
    }
})

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
<input type="text" id="number">
<p id="result"></p>