2

I'm trying to make a calculation using number fields that have set decimal places.

While the decimals are being displayed properly, the calculation is not running. Here is my javascript:

 function setZeroNumberDecimal(el) {
    el.value = parseFloat(el.value).toFixed(0);
};
 function setThreeNumberDecimal(el) {
    el.value = parseFloat(el.value).toFixed(3);
};

$(document).ready(function(){
$(".calc").keyup(function(){
      var areasf = +$(".SF").val();
      $("#acre").val(areasf/43560);
});
});

And the HTML:

  <input type="number" onchange="setZeroNumberDecimal(this)" name="grosslandSF" class="calc SF">
  <input type="number" onchange="setThreeNumberDecimal(this)" name="grosslandacre" disabled="disabled" id="acre">

Any help would be great.

MAM
  • 56
  • 9
  • Check out this [answer](http://stackoverflow.com/a/34057860/4824627) and this [answer](http://stackoverflow.com/a/22654797/4824627) and this [answer](http://stackoverflow.com/q/19011861/4824627), the `step` might be the issue here – Matheus Avellar Feb 26 '17 at 21:00
  • 1
    The decimals weren't the issue. It was the calculation. – MAM Feb 26 '17 at 21:21

1 Answers1

0

Instead of inline onchange event you can use oninput event.

When you change a value like in:

$("#acre").val(areasf/43560)

this will not fire the corresponding event, so you must do it by yourself:

$("#acre").val(areasf/43560).trigger('input');

The snippet:

function setZeroNumberDecimal(el) {
    el.value = parseFloat(el.value).toFixed(0);
};
function setThreeNumberDecimal(el) {
    el.value = parseFloat(el.value).toFixed(3);
};

$(document).ready(function(){
    $(".calc").keyup(function(){
        var areasf = +$(".SF").val();
        $("#acre").val(areasf/43560).trigger('input');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form>
    <input type="number" oninput="setZeroNumberDecimal(this)" name="grosslandSF" class="calc SF">
    <input type="number" oninput="setThreeNumberDecimal(this)" name="grosslandacre" disabled="disabled" id="acre">
</form>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • Thank you, the calc is running and sticking to 3 decimals. However, if you put in 43560, the result is 1, whereas it should be 1.000 (it's a land thing with acres, should always result in 3 decimals even if a whole number) – MAM Feb 26 '17 at 21:14
  • @MichaelM Indeed, if you input 43560 the result is 1.000. Which browser are you using? – gaetanoM Feb 26 '17 at 21:17
  • 1
    You are correct. I forgot to change my onchange to oninput. Thank you, gaetanoM. You saved me a huge headache! – MAM Feb 26 '17 at 21:21