两种货币的货币换算

时间:2018-12-16 12:44:17

标签: javascript jquery rest

我目前正在使用货币转换器,并且需要有关如何使用户能够选择他们想要的货币的帮助,就像currencyFrom。

当前,转换仅从USD(设置为1)开始,然后转换为选定的货币。如何允许用户选择除USD之外的其他货币,它仍然可以计算正确的汇率?

/* Connecting HTML currency form with the functionality from JavaScript 
We create a function to convert currencies using API and the value entered by the user.

*/
var calculate = function calculate() {
  
    var amount = parseFloat(document.getElementById("amount").value); // Sets the varaible amount to be connected with whatever value the user types in the amount field in HTML
    var select1 = document.getElementById("currencyTo"); // Sets the variable select1 to be connected with currencyTo in HTML 
    var result = document.getElementById("result"); // Sets the variable result to be connected with result in HTML 

/* The calculation for the selected rates
The calculation times the amount the user types with the currency and rate related to the currency
And defines this number equals result
*/
    var number = amount * select1.options[select1.selectedIndex].dataset.rate; 
     result.value = number;
}
  
// The calculate function is initiated as soon as the user types a number in the amount field or change the currency, and displays the result immediately in the result field
// This element allows the user to see the immediate result without pressing a calculate button

  document.getElementById("amount").addEventListener("keyup", calculate);
  document.getElementById("currencyTo").addEventListener("change", calculate);

 /* This defines currencies and rates connected witht the specific currency 
The key is the abbreviation of the currency name and the value is the rate connected to each currency*/

function callbackFunc(response){ 
    var currencies = response; 
    var currencies_keys = Object.keys(currencies.quotes); 
    var currencies_values = Object.values(currencies.quotes);

//This ensures that the user can not change the default currency in the currencyFrom field 
    var currencyFrom = document.getElementById("currencyFrom");
    currencyFrom.setAttribute("disabled", "disabled"); 

// When define that the currencies and its values shoud go to the currencyTo field 
    var currencyTo = document.getElementById("currencyTo");
    var currencySelection = "";

// Here we use a universal function to retrieve the activeUser key from LocalStorage as a string and transforms the values into JavaScript objects using JSON.parse
    var activeUser = JSON.parse(localStorage.getItem('activeUser'))
   
// This creates a list of all the currencies 
    var currenciesList = [];

    for(i=0; i < currencies_keys.length; i++){
        if(i == 0){
            var currency = currencies_keys[i].substring(0,3); // With this substring we split the currencyFrom and currencyTo into their own strings
        
        }

// With this substring we split the currencyFrom and currencyTo into their own strings and define variables
// And defines that the varibale rate should inherit the values of the currenices_values, which is currencies and quotes  
        var currency = currencies_keys[i].substring(3,6);
        var rate = currencies_values[i];

// Create a variable called currency object that consists of the variables currency and rate 
// Push the object into the currency list 
// We tell our currency converter that whatever the currency the user picks it should inherit the values of the variable currency and rate
        var currencyObject = new Currency(currency, rate);
        currenciesList.push(currencyObject);

        currencySelection += "<option value='" + currency + "' data-rate='" + rate + "'>" + currency + "</option>";
    }
//  Adding the list of currency objects to local storage and transforming the list to a string and displaying predefined currency from activeUser in currencyTo in HTML 
    localStorage.setItem("currencies", JSON.stringify(currenciesList));

    currencyTo.innerHTML = currencySelection;

    currencyTo.value = activeUser.currency.name; 
 }

// set endpoint and your access key
endpoint = 'live'
access_key = '7ff7413fd18c1b9652f371629bd4bb4f';

// Here we get the most recent exchange rates via the "live" endpoint:
$.ajax({
    url: 'http://apilayer.net/api/' + endpoint + '?access_key=' + access_key,   
    dataType: 'jsonp',
    success: function(json) {
        callbackFunc(json);  
    }
});

//Logout function - redirects to LogIn html when button is clicked
var logout = document.getElementById('logout');
logout.onclick = function() {
    document.location.href = 'login1.html'; 
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Main page</title>
    <link rel="stylesheet" href="mainpage.css">
    <link rel="stylesheet" href="commentbox.css">
    <!--Link to external font from google-->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">

    <!--In order for our program to collect rates using API we need to fetch a third party script that are created with ajax and JQuery-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
  </head>
  <body>

      <div class="background" style="background-image:url(https://images.unsplash.com/photo-1524821695732-717b25a38974?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=08f92fcbaca12ac3d128dbc91f447164&auto=format&fit=crop&w=1200&q=80)">
            <h3 class="headline">Currency Converter</h3>
            </div>
  

<!-- Left side Currency converter-->
<div class="float-left" style="width:49%; float: left;">
    <div style="text-align:center">

<!--Currency converter-->
<h5>Currency converter</h5>

<!-- We created a form for the currency conversion-->

<form>
<p>
<input type="text" placeholder="Insert numbers" id="amount" value=""  style="height:40px;font-size:12pt;width:350px;">
<br>
<br>
<!--This field is set to USD as default which is CurrencyFrom-->
<select id="currencyFrom"style="height:50px;font-size:14pt;width:150px">
    <option value='AED' title='United Arab Emirates Dirham'>AED</option>
   <option value='AFN' title='Afghan Afghani'>AFN</option>
   <option value='ALL' title='Albanian Lek'>ALL</option>
   <option value='AMD' title='Armenian Dram'>AMD</option>
   <option value='ANG' title='Netherlands Antillean Guilder'>ANG</option>
   <option value='AOA' title='Angolan Kwanza'>AOA</option>
   <option value='ARS' title='Argentine Peso'>ARS</option>
   <option value='AUD' title='Australian Dollar'>AUD</option>
   <option value='AWG' title='Aruban Florin'>AWG</option>
   <option value='AZN' title='Azerbaijani Manat'>AZN</option>
   <option value='BAM' title='Bosnia-Herzegovina Convertible Mark'>BAM</option>
   <option value='BBD' title='Barbadian Dollar'>BBD</option>
   <option value='BDT' title='Bangladeshi Taka'>BDT</option>
   <option value='BGN' title='Bulgarian Lev'>BGN</option>
   <option value='BHD' title='Bahraini Dinar'>BHD</option>
   <option value='BIF' title='Burundian Franc'>BIF</option>
   <option value='BMD' title='Bermudan Dollar'>BMD</option>
   <option value='BND' title='Brunei Dollar'>BND</option>
   <option value='BOB' title='Bolivian Boliviano'>BOB</option>
   <option value='BRL' title='Brazilian Real'>BRL</option>
   <option value='BSD' title='Bahamian Dollar'>BSD</option>
   <option value='BTC' title='Bitcoin'>BTC</option>
   <option value='BTN' title='Bhutanese Ngultrum'>BTN</option>
   <option value='BWP' title='Botswanan Pula'>BWP</option>
   <option value='BYN' title='Belarusian Ruble'>BYN</option>
   <option value='BYR' title='Belarusian Ruble'>BYR</option>
   <option value='BZD' title='Belize Dollar'>BZD</option>
   <option value='CAD' title='Canadian Dollar'>CAD</option>
   <option value='CDF' title='Congolese Franc'>CDF</option>
   <option value='CHF' title='Swiss Franc'>CHF</option>
   <option value='CLF' title='Chilean Unit of Account (UF)'>CLF</option>
   <option value='CLP' title='Chilean Peso'>CLP</option>
   <option value='CNY' title='Chinese Yuan'>CNY</option>
   <option value='COP' title='Colombian Peso'>COP</option>
   <option value='CRC' title='Costa Rican Colón'>CRC</option>
   <option value='CUC' title='Cuba Convertible Peso'>CRC</option>
   <option value='CUP' title='Cuban Peso'>CUP</option>
   <option value='CVE' title='Cape Verdean Escudo'>CVE</option>
   <option value='CZK' title='Czech Republic Koruna'>CZK</option>
   <option value='DJF' title='Djiboutian Franc'>DJF</option>
   <option value='DKK' title='Danish Krone'>DKK</option>
   <option value='DOP' title='Dominican Peso'>DOP</option>
   <option value='DZD' title='Algerian Dinar'>DZD</option>
   <option value='EEK' title='Estonian Kroon'>EEK</option>
   <option value='EGP' title='Egyptian Pound'>EGP</option>
   <option value='ERN' title='Eritrean Nakfa'>ERN</option>
   <option value='ETB' title='Ethiopian Birr'>ETB</option>
   <option value='EUR' title='Euro'>EUR</option>
   <option value='FJD' title='Fijian Dollar'>FJD</option>
   <option value='FKP' title='Falkland Islands Pound'>FKP</option>
   <option value='GBP' title='British Pound Sterling'>GBP</option>
   <option value='GEL' title='Georgian Lari'>GEL</option>
   <option value='GGP' title='Guernsey Pound'>GGP</option>
   <option value='GHS' title='Ghanaian Cedi'>GHS</option>
   <option value='GIP' title='Gibraltar Pound'>GIP</option>
   <option value='GMD' title='Gambian Dalasi'>GMD</option>
   <option value='GNF' title='Guinean Franc'>GNF</option>
   <option value='GTQ' title='Guatemalan Quetzal'>GTQ</option>
   <option value='GYD' title='Guyanaese Dollar'>GYD</option>
   <option value='HKD' title='Hong Kong Dollar'>HKD</option>
   <option value='HNL' title='Honduran Lempira'>HNL</option>
   <option value='HRK' title='Croatian Kuna'>HRK</option>
   <option value='HTG' title='Haitian Gourde'>HTG</option>
   <option value='HUF' title='Hungarian Forint'>HUF</option>
   <option value='IDR' title='Indonesian Rupiah'>IDR</option>
   <option value='ILS' title='Israeli New Sheqel'>ILS</option>
   <option value='IMP' title='Manx pound'>IMP</option>
   <option value='INR' title='Indian Rupee'>INR</option>
   <option value='IQD' title='Iraqi Dinar'>IQD</option>
   <option value='IRR' title='Iranian Rial'>IRR</option>
   <option value='ISK' title='Icelandic Króna'>ISK</option>
   <option value='JEP' title='Jersey Pound'>JEP</option>
   <option value='JMD' title='Jamaican Dollar'>JMD</option>
   <option value='JOD' title='Jordanian Dinar'>JOD</option>
   <option value='JPY' title='Japanese Yen'>JPY</option>
   <option value='KES' title='Kenyan Shilling'>KES</option>
   <option value='KGS' title='Kyrgystani Som'>KGS</option>
   <option value='KHR' title='Cambodian Riel'>KHR</option>
   <option value='KMF' title='Comorian Franc'>KMF</option>
   <option value='KPW' title='North Korean Won'>KPW</option>
   <option value='KRW' title='South Korean Won'>KRW</option>
   <option value='KWD' title='Kuwaiti Dinar'>KWD</option>
   <option value='KYD' title='Cayman Islands Dollar'>KYD</option>
   <option value='KZT' title='Kazakhstani Tenge'>KZT</option>
   <option value='LAK' title='Laotian Kip'>LAK</option>
   <option value='LBP' title='Lebanese Pound'>LBP</option>
   <option value='LKR' title='Sri Lankan Rupee'>LKR</option>
   <option value='LRD' title='Liberian Dollar'>LRD</option>
   <option value='LSL' title='Lesotho Loti'>LSL</option>
   <option value='LTL' title='Lithuanian Litas'>LTL</option>
   <option value='LVL' title='Latvian Lats'>LVL</option>
   <option value='LYD' title='Libyan Dinar'>LYD</option>
   <option value='MAD' title='Moroccan Dirham'>MAD</option>
   <option value='MDL' title='Moldovan Leu'>MDL</option>
   <option value='MGA' title='Malagasy Ariary'>MGA</option>
   <option value='MKD' title='Macedonian Denar'>MKD</option>
   <option value='MMK' title='Myanma Kyat'>MMK</option>
   <option value='MNT' title='Mongolian Tugrik'>MNT</option>
   <option value='MOP' title='Macanese Pataca'>MOP</option>
   <option value='MRO' title='Mauritanian Ouguiya'>MRO</option>
   <option value='MUR' title='Mauritian Rupee'>MUR</option>
   <option value='MVR' title='Maldivian Rufiyaa'>MVR</option>
   <option value='MWK' title='Malawian Kwacha'>MWK</option>
   <option value='MXN' title='Mexican Peso'>MXN</option>
   <option value='MYR' title='Malaysian Ringgit'>MYR</option>
   <option value='MZN' title='Mozambican Metical'>MZN</option>
   <option value='NAD' title='Namibian Dollar'>NAD</option>
   <option value='NGN' title='Nigerian Naira'>NGN</option>
   <option value='NIO' title='Nicaraguan Córdoba'>NIO</option>
   <option value='NOK' title='Norwegian Krone'>NOK</option>
   <option value='NPR' title='Nepalese Rupee'>NPR</option>
   <option value='NZD' title='New Zealand Dollar'>NZD</option>
   <option value='OMR' title='Omani Rial'>OMR</option>
   <option value='PAB' title='Panamanian Balboa'>PAB</option>
   <option value='PEN' title='Peruvian Nuevo Sol'>PEN</option>
   <option value='PGK' title='Papua New Guinean Kina'>PGK</option>
   <option value='PHP' title='Philippine Peso'>PHP</option>
   <option value='PKR' title='Pakistani Rupee'>PKR</option>
   <option value='PLN' title='Polish Zloty'>PLN</option>
   <option value='PYG' title='Paraguayan Guarani'>PYG</option>
   <option value='QAR' title='Qatari Rial'>QAR</option>
   <option value='RON' title='Romanian Leu'>RON</option>
   <option value='RSD' title='Serbian Dinar'>RSD</option>
   <option value='RUB' title='Russian Ruble'>RUB</option>
   <option value='RWF' title='Rwandan Franc'>RWF</option>
   <option value='SAR' title='Saudi Riyal'>SAR</option>
   <option value='SBD' title='Solomon Islands Dollar'>SBD</option>
   <option value='SCR' title='Seychellois Rupee'>SCR</option>
   <option value='SDG' title='Sudanese Pound'>SDG</option>
   <option value='SEK' title='Swedish Krona'>SEK</option>
   <option value='SGD' title='Singapore Dollar'>SGD</option>
   <option value='SHP' title='Saint Helena Pound'>SHP</option>
   <option value='SLL' title='Sierra Leonean Leone'>SLL</option>
   <option value='SOS' title='Somali Shilling'>SOS</option>
   <option value='SRD' title='Surinamese Dollar'>SRD</option>
   <option value='STD' title='São Tomé and Príncipe Dobra'>STD</option>
   <option value='SVC' title='Salvadoran Colón'>SVC</option>
   <option value='SYP' title='Syrian Pound'>SYP</option>
   <option value='SZL' title='Swazi Lilangeni'>SZL</option>
   <option value='THB' title='Thai Baht'>THB</option>
   <option value='TJS' title='Tajikistani Somoni'>TJS</option>
   <option value='TMT' title='Turkmenistani Manat'>TMT</option>
   <option value='TND' title='Tunisian Dinar'>TND</option>
   <option value='TOP' title='Tongan Pa?anga'>TOP</option>
   <option value='TRY' title='Turkish Lira'>TRY</option>
   <option value='TTD' title='Trinidad and Tobago Dollar'>TTD</option>
   <option value='TWD' title='New Taiwan Dollar'>TWD</option>
   <option value='TZS' title='Tanzanian Shilling'>TZS</option>
   <option value='UAH' title='Ukrainian Hryvnia'>UAH</option>
   <option value='UGX' title='Ugandan Shilling'>UGX</option>
   <option value='USD' title='United States Dollar'>USD</option>
   <option value='UYU' title='Uruguayan Peso'>UYU</option>
   <option value='UZS' title='Uzbekistan Som'>UZS</option>
   <option value='VEF' title='Venezuelan Bolívar'>VEF</option>
   <option value='VND' title='Vietnamese Dong'>VND</option>
   <option value='VUV' title='Vanuatu Vatu'>VUV</option>
   <option value='WST' title='Samoan Tala'>WST</option>
   <option value='XAF' title='CFA Franc BEAC'>XAF</option>
   <option value='XAG' title='Silver (troy ounce)'>XAG</option>
   <option value='XAU' title='Gold (troy ounce)'>XAU</option>
   <option value='XCD' title='East Caribbean Dollar'>XCD</option>
   <option value='XDR' title='Special Drawing Rights'>XDR</option>
   <option value='XOF' title='CFA Franc BCEAO'>XOF</option>
   <option value='XPF' title='CFP Franc'>XPF</option>
   <option value='YER' title='Yemeni Rial'>YER</option>
   <option value='ZAR' title='South African Rand'>ZAR</option>
   <option value='ZMK' title='Zambian Kwacha (pre-2013)'>ZMK</option>
   <option value='ZMW' title='Zambian Kwacha'>ZWL</option>
   <option value='ZWL' title='Zimbabwean Dollar'>ZWL</option>
</select> 

<!--This is currencyTo where the user can chose the preferred rate. The default will be the rate selected at registration-->
<select id="currencyTo" style="height:50px;font-size:14pt;width:150px">
</select>

<br>
<br>

<!--Here the user will see the calculated result-->
<input type="text" id="result" value="" style="height:40px;font-size:12pt;width:350px; background-color:lightsteelblue">
</p>
</form> 

<!--This button allows users to log out and return to the login page-->
<div id="Footer">
  <input 
  type="button" 
  value="Logout" 
  name="logout" 
  id="logout" />
  </div>

</div>
</div>


<!-- This is the right part of the page, where the comment box is placed -->
<div class="float-right" style="width:49%; float: right;">
  <div class="content">
  <div class="comments">
  <div class="editor">
  <div class="editor-header">
    <a href='#' data-role='bold'>B</a>
    <a href='#' data-role='italic'>I</a>
    <a href='#' data-role='underline'>U</a>
    <a href='#' data-role='justifyleft'><i class="menu-left"></i></a>
    <a href='#' data-role='justifycenter'><i class="menu-center"></i></a>
    <a href='#' data-role='justifyright'><i class="menu-right"></i></a>
  </div>

  <div id="text" class="editor-content" contenteditable palceholder= "Leave a comment">
  </div>
  </div>
                  
  <div class="insert-text">
    <span class="loading">Loading...</span>
    <!--This span class calculates the total comments-->
    <span class="total-comment"></span>
        <p>
        <input type="submit" value="Comment" />
        </p>
  </div>
    <div class="listComments">
                
  </div>
  </div>
</div>
</div>
    



<script src="mainpage.js"></script>
<script src="commentbox.js"></script>
<script src ="userclass.js"></script>
<script src="currencyClass.js"></script>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

如果您将USD转换为任何货币,则可以使用该信息通过与USD进行兑换来将任何货币转换为其他货币。 €-> $->£

答案 1 :(得分:0)

这很简单:如果您想计算一个货币对的汇率(例如XXX / YYY),但是只有python script.pyUSD/XXX,只需将第一个(1 / x)反转为设为USD/YYY,然后乘以秒。

例如,您想要XXX/USD

  • 您有GBP/EUR = 0.771188
  • 您有USD/GBP = 0.848514
  • 反转USD/EUR = USD/GBP = 1 / 0.771188 = 1.2967
  • ➡️GBP/USD = GBP/EUR * GBP/USD(注意:USD/EUR取消了)= 1.2967 * 0.848514 = 1.100269

如果需要USD,反之亦然,将EUR/GBP取反并乘以USD/EUR。始终确保您的“中间”汇率(在这种情况下为USD/GBP)居中,这样就消除了。

通过这个简单的技巧,即使在免费计划中,您也可以使用SWOP foreign exchange rate API之类的任何货币API来计算任何基础货币的汇率。

免责声明:我是SWOP的程序员之一;)

另一种说明:通常,您应该避免在帖子中加入USD-人们可能会盗用它并用完您的配额。

最诚挚的问候