Need help with jQuery

Posted 5 months ago by hjortur17

Hi, I'm building a currency converter for my app using an API. I'm trying to make it possible to put the amount in input and it will display how much it is. I'm trying to have it like this:

Before you type anything in the input it will display how much 1 ISK is in EUR, USD and GBP and then if you insert anything to the input it will calculate that. And right now it's always stuck with the value of 1 ISK.

This is my jQuery code:

$(document).ready(function () {
    $.ajax({
        'url': 'https://apis.is/currency/arion',
        'type': 'GET',
        'dataType': 'json',
        'success': function(response) {
            console.log(response);

            var text_ISK    =   response.results[0].shortName;
            var text_EUR    =   response.results[3].shortName;
            var text_USD    =   response.results[1].shortName;
            var text_GBP    =   response.results[2].shortName;

            var input_ISK    =   response.results[0].value;
            var input_EUR    =  response.results[3].value;
            var input_USD    =  response.results[1].value;
            var input_GBP    =  response.results[2].value;

            $('#text_ISK').append(text_ISK);
            $('#text_EUR').append(text_EUR);
            $('#text_USD').append(text_USD);
            $('#text_GBP').append(text_GBP);

            var first_val_eur = input_ISK / input_EUR;
            var first_val_usd = input_ISK / input_USD;
            var first_val_gbp = input_ISK / input_GBP;

            $('#ISK').val(input_ISK);
            $('#EUR').val(first_val_eur.toFixed(2));
            $('#USD').val(first_val_usd.toFixed(2));
            $('#GBP').val(first_val_gbp.toFixed(2));

            $(".calc").bind("keyup change", function(e) {
                var val_eur = input_ISK / input_EUR;
                var val_usd = input_ISK / input_USD;
                var val_gbp = input_ISK / input_GBP;

                if (!isNaN(val_eur) && val_eur !== Infinity) {
                    $("#EUR").val(val_eur.toFixed(2));
                }

                if (!isNaN(val_usd) && val_usd !== Infinity) {
                    $("#USD").val(val_usd.toFixed(2));
                }

                if (!isNaN(val_gbp) && val_gbp !== Infinity) {
                    $("#GBP").val(val_gbp.toFixed(2));
                }
            });
        }
    });


});

Please sign in or create an account to participate in this conversation.