0

I am trying to perform a calculation where the number entered by the user in the first input is returned in the readonly second input field instantly. Its a simple calculation to take 20% of the first number and add it back to the first number, to be returned in the second number field. (e.g 20% transfer fees on $100 would return $120.

It seems I am able to access the values in the input fields, but the returned calculation is not returning the correct values. If 40 is entered in the first input, the returned second input displays 408 instead of 48. Can someone help?

function myFunc() {
  const transferamount = document.getElementById("sendamount").value;
  document.getElementById("totalled").value = transferamount + (0.20 * transferamount);
}
<form>
  <input type="number" id="sendamount" value="" name="amounttosend" oninput="myFunc()" required>

  <input type="text" id="totalled" value="" readonly>
</form>
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Obaka Torto
  • 11
  • 1
  • 2

1 Answers1

0

the value you get from an input is always considered as a string, that's why your calculations are incorrect. To perform as expected you need to convert your input to an int or a float using parseInt() or parseFloat()

const transferamount = parseInt(document.getElementById("sendamount").value);
thomasdqr
  • 11
  • 3
  • 1
    thanks for this useful info. But explain why an input tag with type number, needs to be converted to an int when the field only accept numbers. why can't I just access such an input field type number with just the value defined or entered by the user? – Obaka Torto Jun 26 '22 at 13:52
  • This is actually due to the way the html input component works, unfortunately there is nothing you can do about it. However there is an alternate way to do it. Actually, instead of accessing "value" you can use "valueAsNumber" ```const transferamount = document.getElementById("sendamount").valueAsNumber ``` – thomasdqr Jun 27 '22 at 17:45