1

I created a Bitcoin (BTC) to Canadian Dollar (CAD) converter that uses the current price from a different site, now I am trying to limit the values acceptable for the BTC/CAD inputs but it doesn't work. The limits I want to set is $2 to $99.99 for CAD and the BTC equivalent for max/min but it doesn't want to work...

Fiddle: https://jsfiddle.net/z735tswj/ all the relevant code is in the html tab or below

<input id="btcc" type="text" onkeyup="btcConvert()" onchange="btcCheck()">BTC</input>

<input id="cadc" type="text" onkeyup="cadConvert()" onchange="cadCheck()">CAD</input>
<br>
<br>

<script>
  function btcConvert() {
    var btc = document.getElementById("btcc").value;
    var btcCalc = btc * price;
    var btcCalc = btcCalc.toFixed(2);
    document.getElementById("cadc").value = btcCalc;
    btcCheck();
  }

  function cadConvert() {
    var cad = document.getElementById("cadc").value;
    var cadCalc = cad / price;
    var cadCalc = cadCalc.toFixed(8);
    document.getElementById("btcc").value = cadCalc;
    cadCheck();
  }

  function btcCheck() {
    if (btc.value < 0.001649) btc.value = 0.001649;
    if (btc.value > 0.082259) btc.value = 0.082259;
    btcConvert();
  }

  function cadCheck() {
    if (cad.value < 2) cad.value = 2;
    if (cad.value >= 100) cad.value = 99.99;
    cadConvert();
  }

</script>
NipBoss
  • 153
  • 1
  • 2
  • 13

2 Answers2

2

Got it working, your script was not passing the input value to cadCheck()

I just made a few edits to get it to work. cadCheck() will get the value of the input before running cadConvert().

function cadCheck(input) { 
 if (input.value < 2) input.value = 2;
 if (input.value >= 100) input.value = 99.99;
 cadConvert();
 }

I also took out the onkeyup="cadConvert() because you are calling that in cadCheck() and added this("this" being the input's value) to onchange="cadCheck().

new html <input id="cadc" type="text" onchange="cadCheck(this)">CAD</input>

Here is my code https://jsfiddle.net/so7s9efr/

Paul Allen
  • 351
  • 2
  • 10
0

Don't mean to be the "just use this" guy, but currency conversion is a common, solved problem and there are many good solutions out there.

A good one is money.js

Was working on a fiddle solution, but Paul Allen's works fine.

theannouncer
  • 1,148
  • 16
  • 28