[英]Divide text field input by set number, show result
I have a text field that I need to divide by certain inputs.我有一个文本字段,需要除以某些输入。 I've tried using the code below but I am running in to issues.我试过使用下面的代码,但我遇到了问题。 It does not take the decimal point in to account, and will return 0 if you use a decimal.它不考虑小数点,如果使用小数点,将返回 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>
So for example if someone inputs their sensitivity in the text box as 1.2
, it would then do 1.2 / 3.181818 = 0.37714287869
因此,例如,如果有人在文本框中输入他们的灵敏度为1.2
,那么它将执行1.2 / 3.181818 = 0.37714287869
0.37714287869
being their new sensitivity. 0.37714287869
是他们的新灵敏度。
Remove the toFixed
and set div
as a float 3.181818
:删除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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.