Automatically updating the USD amount when changed using onchange event in JavaScript

https://i.sstatic.net/SjxRl.pngI am struggling with this code and despite looking at numerous related questions, I have not found a solution that works. Can someone please assist me? Here are the specific things I need help with:

  1. I need to automatically update the "Amount(USD)" when the value of "Amount(NGN)" is changed. Ideally, I would like to achieve this using Vanilla JS.

  2. Additionally, I want to retrieve the final value of "Amount(USD)", store it in a PHP session, and use it on other pages.

Below is the code snippet I am working with:

<?php $grandTotal=10; ?>

<script type="text/javascript>
  function calculateTotal() {

    var nairaRate = document.pricecalculator.nairaRateToday.value; //get NGN rate today from admin and assign to nairaRate


    dollarValue = eval(document.pricecalculator.nairaInput.value * nairaRate); //multiply nairaInput by nairaRate to get dollarValue


    document.getElementById('dollar').innerHTML = dollarValue; //pass dollarValue to dollar to show auto-calculation onscreen
  }
</script>

<form name="pricecalculator" action="">
  <legend>Price Calculator (Buy BTC)</legend>
  <label>Amount (NGN)</label><input type="number" name="nairaInput" onchange="calculateTotal()" value="1" /> <br />
  <label>Amount (USD):</label><span id="dollar">1</span> <br />
  <input type="hidden" name="nairaRateToday" value="<?= $grandTotal ?>">
</form>

Answer №1

This problem was successfully resolved using the following method:

<?php $grandTotal=10; ?> // initializing PHP variable


        <form name="pricecalculator" action=""> 
            <legend>Price Calculator (Buy BTC)</legend>
            <label>Amount (NGN)</label><input type="number" id="naira-input" name="naira-input" onchange="calculateTotl()" value="1"/> <br />
            <label>Amount (USD):</label><span id="dollar">1</span> <br />
        </form>


        <script type="text/javascript">
            function calculateTotl() {
                var nairaRate = document.getElementById("naira-input").value;
                // Getting the current input

                let phpval = "<?= $grandTotal ?>"; // fetching PHP value
                
                    var dollarResult = document.querySelector('#dollar'); 
                    var total = Number(nairaRate) * Number(phpval); // calculating current input * php value
                  return dollarResult.innerHTML = total; // displaying result in #dollar element
                }
        </script>

Answer №2

Check out this solution that has proven to be effective:

let euro = document.getElementById('euro');
let dollar = document.getElementById('dollar');
euro.onchange = ()=>{dollar.innerText=euro.value*0.0032}

Answer №3

Review the code snippet provided below. A hardcoded value of 7 is used as the nairaRate

let nairaInput = document.querySelector("input[name='NairaValue']")

nairaInput.addEventListener('change', (e) => calculateTotal(e.target.value, 7))

function calculateTotal(input, nairaRate) {
  var resultInDollar = document.querySelector('#dollar');
  var total = Number(input) / Number(nairaRate);
  return resultInDollar.innerHTML = total
}
<form name="pricecalculator" action="">
  <legend>Price Calculator (Buy BTC) Naira At 7</legend>
  <label>Amount (NGN)</label><input type="number" name="NairaValue" onchange="calculateTotal()" value="0" /> <br />
  <label>Amount (USD):</label><span id="dollar">0</span> <br />
  <input type="hidden" name="nairaRateToday" value="<?= $grandTotal ?>">
</form>

Best of luck!

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

AngularJS secondary controller experiencing malfunctions

Having an issue with my second controller (RegisterController) in the module I've created. The first one is working perfectly fine. I have both controllers in a file named user.js var app = angular.module("User", []); app.controller('LoginCont ...

What is the best way to compile TypeScript files without them being dependent on each other?

I have created a TypeScript class file with the following code: class SampleClass { public load(): void { console.log('loaded'); } } Now, I also have another TypeScript file which contains functions that need to utilize this class: // ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

What is the best way to display multiple canvases on one page?

Is it possible to draw multiple canvases in a single page using this code? I have successfully drawn a single canvas using the provided code. For each canvas, I have different y data and I need to display 6 canvases per page. How can I achieve this on a ...

What is the process for configuring MySQL connections in Node.js to generate Out of Range errors when dealing with arithmetic operations involving unsigned integers?

I'm currently utilizing node.js along with the Mysql2 library, which seems to have a connection to the node-mysql library. Within my mysql database, there is an unsigned integer field that I am updating by either adding or subtracting values as detail ...

Performing an Ajax post request to a PHP script in order to retrieve a PHP variable using XMLHttpRequest

I am looking to dynamically update my table using JavaScript every few seconds. Currently, I have set up an AJAX post request to my update.php file and trigger it if it is set. Then, I execute a MySQL query to retrieve the data and store the resultset in ...

Tips for including an external babel JS (ES6) file in an HTML document:

To include the babel js file in an HTML file, take a look at the code snippet below: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudfl ...

The Beauty of Organized Data: Understanding Multiple Columns in VUE JS Projects

I'm currently developing a VUE JS app that calculates route costs for employees based on specific route details. I am looking to create a VUE JS component that will only display a dropdown list with three columns: List of countries Day fee for each ...

How can I send a current variable through PHP?

I have a pressing deadline and I need some guidance before moving forward. Can someone please advise if what I'm attempting is feasible or if there's a quicker solution? I encountered some problems with an accordion menu, so as a temporary fix, ...

Incorporating a stationary navigation bar alongside a parallax scrolling layout

After spending the entire night trying to figure this out, I have had zero success so far. I decided to tackle this issue with javascript since my attempts with CSS have been completely fruitless. This is a demonstration of the parallax scrolling webpage. ...

How come the item I just inserted into a JavaScript array is showing up as undefined when I try to retrieve it immediately after adding it?

Apologies for the messy code, but I'm facing an issue with my JavaScript. I can't figure out why the specified child is not considered as a task to derive from: var childrenToOperateOn = []; for (var i = 0; i < $scope.der ...

Determining the elapsed time using Momentjs

I need assistance with a NodeJS project where I am trying to determine if a specific amount of time (like 1 hour) has passed since creating an object. My project involves the use of MomentJS. For example, if moment(book.createdAt).fromNow() shows 2 hours ...

Exploring elements within a JavaScript array

I'm struggling to retrieve model objects from my view model. It seems like a JavaScript/KnockoutJS familiarity issue, so any guidance is welcomed. Here is the code snippet: <!-- VIEW --> <select data-bind="options: allTypes, ...

Convert JavaScript to TypeScript by combining prototype-based objects with class-based objects

My current challenge involves integrating JavaScript prototype with class-based programming. Here is an example of what I've tried: function Cat(name) { this.name = name; } Cat.prototype.purr = function(){ console.log(`${this.name} purr`) ...

Searching for a way to detect when a user clicks the back button on their Android or iPhone device using JavaScript or

In the process of building a Single Page Application (HTML5) utilizing the following plugins: - Sammy.js - Knockout.js - Require.js - Jquery.js This app is designed for Android, iPhone, and Windows mobile devices. Many scenarios revolve around cli ...

Steps for adding products to your shopping cart without using a JavaScript framework:

As a newcomer to web development, I took on the challenge of creating an e-commerce website using only HTML, CSS, and vanilla JavaScript (without any frameworks). I've encountered a roadblock while trying to implement the "Add to Cart" functionality ...

React: Error parsing - Missing closing JSX tag for <input> element

I am currently learning React and am in the process of working on a new component. Here is the code snippet that I have so far: order-item.component.jsx: import React, { Component } from 'react'; import { connect } from 'react-redux'; ...

Tips for refreshing innerHTML without altering the entire content

I've written a JavaScript code that uses AJAX to periodically send an XMLHttpRequest to fetch data from a PHP file. The data retrieved is then added to the innerHTML of a <p> tag. However, every time new content is added, the entire paragraph se ...

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

Scanning barcode and Qrcode with Angular js HTML5 for seamless integration

Looking to scan Barcode and Qrcode on Android, iPhone, and iPad devices for a project that is built on AngularJS and HTML5 as a mobile website. The requirement is not to download any third-party native application on the device, ruling out the use of nati ...