将文本字段输入除以设置编号,显示结果

时间:2020-04-05 19:31:26

标签: javascript jquery html math

我有一个文本字段,需要按某些输入进行划分。我尝试使用下面的代码,但遇到了问题。它不考虑小数点,如果使用小数,则将返回0。

<input id="number" type="text"> ÷ 3.181818<br />
Your output is: <div id="output"></div>

<script type="text/javascript">
//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 = '3.181818'; // 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!';
  }
});
</script>

例如,如果某人在文本框中输入自己的敏感度为1.2,则它将执行1.2 / 3.181818 = 0.37714287869

0.37714287869是他们的新敏感度。

1 个答案:

答案 0 :(得分:2)

删除toFixed并将div设置为浮动3.181818

//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 = 3.181818; // 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)) {

    output.innerHTML = val / division;
  } else {
    output.innerHTML = 'that\'s not a number!';
  }
});
<input id="number" type="text"> ÷ 3.181818<br /> Your output is:
<div id="output"></div>