Currency Conversion Rates Showcased

Why does the exchange rate consistently show as N/A in the code below after selecting a currency pair, and how can this issue be resolved effectively?

I anticipate that the exchange rate value will be displayed accurately once a pair is selected.

What steps should I take to rectify this and display the rates correctly?

Are there any recommended libraries available for better conversion?

{% extends "app/base.html" %}
{% block content %}
<head>
    <title>Cross-Border Payment App</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f2f2f2;
            padding: 20px;
        }
    
        form {
            width: 80%;
            padding: 20px;
            background-color: #ffffff;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
    
        h1 {
            text-align: center;
            color: #333333;
            cursor: pointer; /* Add cursor style to indicate it's clickable */
        }
    
        h1:hover {
            text-decoration: underline; /* Add underline effect on hover */
        }
    
        label {
            font-weight: bold;
        }
    
        input[type="text"],
        select {
            width: 100%;
            padding: 10px;
            border: 3px solid #ccc;
            border-radius: 4px;
            margin-bottom: 10px;
        }
    
        input[type="submit"] {
            width: 100%;
            padding: 10px 20px;
            background-color: #4CAF50;
            color: #ffffff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    
        input[type="submit"]:hover {
            background-color: #45a049;
        }
    
        .exchange-rate {
            font-size: 14px;
            font-style: italic;
            color: #999999;
            margin-top: 5px;
        }
    
        select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        email {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-bottom: 10px;
        }
    
        .bank-options {
            border: 1px solid #ccc;
            border-radius: 4px;
            max-height: 100px;
            overflow-y: auto;
            padding: 5px;
        }
    
        .bank-option {
            cursor: pointer;
            padding: 5px;
        }
    
        .bank-option:hover {
            background-color: #f2f2f2;
        }
    
        .bank-option.disabled {
            color: #999999;
            cursor: not-allowed;
        }
    </style>    
    
  </head>
    <body>
        <h1>Glocal Payments</h1>
        <form method="post" action="{% url 'glocal' %}" onsubmit="return validatePaymentAmount()">
            {% csrf_token %}
        
            <div class="form-field">
                <label for="sender_name">Sender's Name:</label>
                <input type="text" name="sender_name" id="sender_name">
            </div>
        
            <div class="form-field">
                <label for="sender_account_number">Sender's Account Number:</label>
                <input type="text" name="sender_account_number" id="sender_account_number">
            </div>
        
            <div class="form-field">
                <label for="sender_country">Sender's Country:</label>
                <select name="sender_country" id="sender_country">
                    <option value="">Select Country</option>
                    <option value="USA">USA</option>
                    <option value="Nigeria">Nigeria</option>
                </select>
            </div>

            <!-- Other form fields omitted for brevity -->

            {% block scripts %}  
            <script>
                function calculateExchangeRate() {
            var senderCurrency = document.getElementById("sender_currency").value;
            var recipientCurrency = document.getElementById("recipient_currency").value;

            // Define the exchange rates
            var exchangeRates = {
              "USD-NGN": 770.00,  // Exchange rate from USD to NGN
              "NGN-USD": 1 / 770.00,  // Exchange rate from NGN to USD
              // Add other currency pairs and their respective exchange rates here
            };

            var currencyPair = senderCurrency + "-" + recipientCurrency;
            var exchangeRate = exchangeRates[currencyPair];

            // Display the exchange rate or "N/A"
            var exchangeRateField = document.getElementById("exchange_rate");
            if (exchangeRateField) {
              if (exchangeRate !== undefined) {
                exchangeRateField.textContent = "Exchange Rate: " + exchangeRate.toFixed(4);
              } else {
                exchangeRateField.textContent = "N/A";
              }
            }
          }

          // Call the calculateExchangeRate function initially and on currency selection change
          document.getElementById("sender_currency").addEventListener("change", calculateExchangeRate);
          document.getElementById("recipient_currency").addEventListener("change", calculateExchangeRate);

          calculateExchangeRate(); // Call it initially to display the exchange rate for the selected currency pair
            </script>
            {% endblock %}
        </form>   
    </body>
  {% endblock %}

Answer №1

In accordance with James' input, the currency selection choices for your selectors are either NGN-USD or USD-NGN, meaning you only require a single select option.

You may consider converting the input value string to a number (for error mitigation) although it's not entirely essential in this scenario.

For simplicity, I have labeled the select element as "conversion."

// Storing relevant elements in variables
const conversionEl = document.querySelector('#conversion');
const amountEl = document.querySelector('#amount');
const rateEl = document.querySelector('#exchange_rate');

// Adding event listeners to the elements
conversionEl.addEventListener('change', calculateExchangeRate);
amountEl.addEventListener('input', calculateExchangeRate);

// Setting up the exchange rates object
const exchangeRates = {
  'NGN-USD': 1 / 770.00,
  'USD-NGN': 770.00
};

function calculateExchangeRate() {
  
  // Retrieving values from the elements
  const conversion = conversionEl.value;
  const amount = Number(amountEl.value);

  // Updating the text content of the rate span by multiplying
  // the amount with the conversion rate specified in the exchangeRates object
  rateEl.textContent = amount * exchangeRates[conversion];
}
body,form{padding:20px}email,input[type=text],select{width:100%;padding:10px;margin-bottom:10px}.bank-option:hover,body{background-color:#f2f2f2}body{font-family:Arial,sans-serif}form{width:80%;background-color:#fff;border-radius:4px;box-shadow:0 2px 4px rgba(0,0,0,.1)}h1{text-align:center;color:#333;cursor:pointer}h1:hover{text-decoration:underline}label{font-weight:700}input[type=text],select{border:3px solid #ccc;border-radius:4px}input[type=submit]{width:100%;padding:10px 20px;background-color:#4caf50;color:#fff;border:none;border-radius:4px;cursor:pointer}input[type=submit]:hover{background-color:#45a049}.exchange-rate{font-size:14px;font-style:italic;color:#999;margin-top:5px}email,select{border:1px solid #ccc;border-radius:4px}.bank-options{border:1px solid #ccc;border-radius:4px;max-height:100px;overflow-y:auto;padding:5px}.bank-option{cursor:pointer;padding:5px}.bank-option.disabled{color:#999;cursor:not-allowed}
<div class="form-field">
  <label for="conversion">Conversion</label>
  <select name="conversion" id="conversion">
    <option value="">Select Currency</option>
    <option value="USD-NGN">USD-NGN</option>
    <option value="NGN-USD">NGN-USD</option>
  </select>
</div>

<div class="form-field">
  <label for="amount">Amount:</label>
  <input type="text" name="amount" id="amount">
</div>

<div class="form-field">
  <label for="exchange_rate">Exchange Rate:</label>
  <span id="exchange_rate" class="exchange-rate"></span>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent content overlap in Tumblr's sidebars by using CSS positioning techniques

I'm facing an issue with my blog on Tumblr where the sidebar keeps overlapping the main content. I have modified a premade template and am trying to position the sidebar in the top right corner using absolute or fixed positioning: #sidebar{ position: ...

An illustration of Agile Web Development With Rails showcases an image placed on top of text

Currently, I am engrossed in the book Agile Web Development With Rails and have encountered a slight hitch on page 96. Following the instructions meticulously from the book, but unfortunately hitting an obstacle as shown below: https://i.sstatic.net/gp ...

Is there something else I should consider while implementing onBlur?

I am currently working on implementing form validation for a React form that I have developed. The process involves using an onChange event to update the state with the value of each text field, followed by an onBlur validation function which checks the va ...

Encounter a critical issue while making a JSON request using Kendo UI

I am facing an issue at my workplace where I need to integrate Angular.js with ASP.NET MVC. Currently, I am trying to build a simple application that features a Kendo UI grid on the front page. In my App.js file, I am fetching data from the Data Controller ...

Is it possible to use response.redirect inside a mongoose query in a node.js app using express?

As I embark on my Node.js app development journey, using Express and Mongoose for the first time, some challenges have surfaced. Let me walk you through the relevant portions of my code. Despite having a smooth run with all other features like database in ...

Ways to guarantee that the factory promise is fulfilled prior to the execution of the

So far, I have always found valuable help by studying existing answers on stackoverflow, but now I've hit a roadblock. I'm currently working on an app that utilizes a directive to generate calendar month boxes. <app2directive class="column_5 ...

Simulate mobile double tap screen resize using either jQuery or Javascript

UPDATE: I have encountered an issue that requires assistance. I am seeking help with implementing a functionality to automatically resize screen contents on mobile devices by calling a DoubleTap. The reason behind this requirement is that when a script up ...

How should I position <script> tags when transferring PHP variables to JavaScript?

I've attempted to find an answer without success due to its specificity. Within the header.php file, which serves as the header of the website, various scripts are included to enable jQuery functionality. Additionally, there is a file called workscri ...

How can I eliminate unnecessary gaps in a CSS slider design?

Currently, I am in the process of learning CSS3 and attempting to create a purely CSS slider. Everything has been going smoothly until I encountered an unexpected padding or margin within my slider. After making some adjustments to the margins, the issue ...

Tips for aligning the list style icon perfectly with the text

I need help aligning text in the center of a customer list style image for an LI element. I've attempted using margins and paddings, but it hasn't worked. Here's the code and screenshot: HTML: <ul class="homeList"> <li>Over ...

Using md-chips and md-select together in multi select mode

I'm having trouble generating md-chips when selecting multiple values from an md-select. Does Md-chips only work with autocomplete analyzers and input fields? <md-chips ng-model="launchAPIQueryParams.type"> <md-select name="launchCalTy ...

Resizable icon next to inline element caused width adjustment

I have a group of individuals listed, each with two elements side by side: a "contact me" button (an 'a' element with a fontawesome icon) and a tag displaying the user type (span element). Some users do not have a tag, and when there is one prese ...

Do I have to specify the protocol when loading jQuery?

Underneath is the code snippet: <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script> <script type="text/javascript"> console.log(jQuery); </script> This code works perfectl ...

I am interested in creating an input range slider using React and TypeScript

This code was used to create a slider functionality import { mainModule } from 'process'; import React, { useState } from 'react'; import styled from 'styled-components'; const DragScaleBar = () => { const [value, setV ...

Manipulating Select2 without using jQuery

Is there a way to manage the select2 component programmatically without using jQuery? I need to execute this code through Selenium, and since I cannot access the jQuery object (as it's bundled with Webpack), I have to control it using pure JS. I atte ...

Adaptable Layouts in Bootsrap Grid

I am currently working with Bootstrap Grid. https://i.sstatic.net/giJOI.png One issue I am facing is when I switch back to my mobile screen, I want the layout to adjust accordingly like https://i.sstatic.net/RYPJm.png I have tried different methods but ...

Obtain the milliseconds when utilizing the new Date().toLocaleTimeString() method

I was working on some code and came across this: v.d = new Date().toLocaleTimeString(); When I ran it, the output looked like this: 20:11:40 As you can see, this displays the time of day down to the second, without milliseconds. This made me wonder if ...

Steps to ensure a variable remains constant across a controller, JS file, and a rendered partial

I am working on rendering a partial viewer using ajax and jQuery. My goal is to assign a variable within the partial based on the link that is clicked. Here is the ERB code: <%=link_to "link1", viewer_path(id: Painting.first), remote: true%> <%= ...

Implementing experimental decorators and type reconciliation in TypeScript - A step-by-step guide

My basic component includes the following code snippet: import * as React from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; export interface Props { }; @withRouter export default class Movies extends R ...

Bootstrap and Rails 6 without webpack: default Bootstrap JavaScript functionality malfunctioning

I recently developed a new rails app using the --skip-webpack-install option, and while the default bootstrap styles are functioning properly, some of the JavaScript components don't seem to be working as expected. Even though my application.js file ...