Search code examples
javascripthtmlcurrency

How can I get a two-way unit / currency converter?


I'm trying to build a very simple two-way currency converter.

I currently have this HTML:

    <input id="amount" name="amount" type="text" value="0" />

    <input id="result" name="discount" type="text" value="0" />

and this javascript:

    $('input').on("click",function () {
    $("#result").val(parseInt($("#amount").val(), 10) *  520);
    });

I would like the converter to work both ways, so that the user can enter the amount in either field, like this.


Solution

  • Have a trigger on keyup. That way, if the #amount-box is triggered, you get the result in the #result box and vice-versa.

    <input id="amount" name="amount" type="text" value="0" />
    <input id="result" name="discount" type="text" value="0" />
    

    And:

    $("#amount").keyup(function(){
        var calculated = $(this).val() * 2;
        $("#result").val(calculated);
    });
    
    $("#result").keyup(function(){
        var calculated = $(this).val() / 2;
        $("#amount").val(calculated);
    });