What is the best way to extract the numerical value from a JavaScript object?

I'm currently working on a web form for a currency exchange demonstration. I have included a snippet of HTML and Javascript code that I have initially implemented.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Currency Exchange</title>
    <link rel="stylesheet" type="text/css" href="styles/styles.css" />
  </head>

  <body>
    <h1>Currency Exchange Rates to US Dollar</h1>
    <select id="currencies" onchange="getCurrency()">
      <option value="">Select a Currency</option>
      <option>UK Pounds</option>
      <option>Euros</option>
      <option>Yen</option>
      <option>Yuan</option>
      <option>Swiss Francs</option>
      <option>Canadian Dollars</option>
    </select>
    <p id="exchangerate"></p>
  </body>
</html>

Apologies for the beginner question. I'm attempting to store currency data in a JavaScript object and display it in a dropdown menu. How can I retrieve the values from the object to populate the dropdown menu?

I've tried storing the data in an object, but it doesn't seem to be working as intended. I'm also unsure if using single quotes for a variable is the correct approach - it's the only method that has worked for me so far.

let rates = {
    UKPounds: 0.75,
    Euros: 0.9,
    Yen: 109.44,
    Yuan: 7.02,
    SwissFrancs: 0.98,
    CanadianDollars: 1.32
  };

Here is my initial solution for retrieving the value. Do you think using a for loop would be a suitable approach here?

let cur_type = document.getElementById('currencies').value; //assign the id 'currencies' to cur_type and get value
  cur_type = cur_type.trim(); // remove all leading and trailing spaces in the string.
  if (rates.hasOwnProperty(cur_type)) { // get the property of rates and add to cur_type
    document.getElementById('exchangerate').innerHTML =
      'One US Dollar buys you ' + rates[cur_type] + ' ' + rates; // get id 'exchangerate' and display in the browser the value of each property followed by the names (rates) of each property.
  }
}

Answer №1

You were so close to the solution:

const conversionRates = {
  "UK Pounds": 0.75,
  "Euros": 0.9,
  "Yen": 109.44,
  "Yuan": 7.02,
  "Swiss Francs": 0.98,
  "Canadian Dollars": 1.32
}

function calculateExchangeRate() {
  let selectedCurrency = document.getElementById('currencies').value.trim()
  let message = selectedCurrency ? "One US Dollar will get you " + conversionRates[selectedCurrency] + " " + selectedCurrency : ""
  document.getElementById("exchangerate").innerHTML = message
}
<h1>Conversion Rates to US Dollar</h1>
<select id="currencies" onchange="calculateExchangeRate()">
  <option value="">Select a Currency</option>
  <option>UK Pounds</option>
  <option>Euros</option>
  <option>Yen</option>
  <option>Yuan</option>
  <option>Swiss Francs</option>
  <option>Canadian Dollars</option>
</select>
<p id="exchangerate"></p>

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

Creating a two-column grid layout using Bootstrap 4 is a simple and efficient process. Let's see how

I've been struggling to get this to display side by side in a two-column grid. Even after following Bootstrap tutorials, I can't seem to make it work. Check out the code below: <div class="row"> <div class="col-md-8 ...

Issue with Material UI select component not displaying the label text

I've been struggling with Material UI's "Select" for quite some time now - spent about 10 hours trying to make it work the way I want. Any help would be greatly appreciated. This question is connected to a previous one: Select MenuItem doesn' ...

What is the best method for obtaining a modified image (img) source (src) on the server side?

Having some trouble with a concept in ASP.Net that's causing me quite the headache. I am fairly new to ASP.Net and struggling with something that seems much easier in PHP. I created an img element with an empty src attribute : <img runat="server" ...

Ways to update the title of a Magento widget

I've added a widget to showcase new products on my Home page and it's displaying perfectly. However, I want to get rid of the title "New Product" that comes with it. This pesky little thing needs to go! https://i.sstatic.net/P0NeS.jpg I'm ...

Updating the $_GET parameter using JQuery when a button is clicked

I'm working on implementing a feature where a series of buttons can update the $_GET['year'] variable on my website. These buttons should function across different pages within my website, such as: example.com example.com/?search=foo exa ...

What is the best way to prevent an element from reaching the border of the screen?

As a JavaScript beginner, I am working on creating a simple game. My objective is to prevent the player (20px x 20px) box from causing the screen to scroll. I want a fixed screen where the player cannot go beyond the edges of the screen. Below are my previ ...

Use Javascript to extract an array of strings enclosed in double quotes

Is there a way to extract an array containing ["13139","13141", "13140"] from the following data structure? { "13139": [tx[0]], "13141": [tx[1]], "13140": [tx[2]] } I attempted to use JS ...

mobile-exclusive wordpress text area problem

There seems to be a padding issue that is only affecting mobile devices. https://i.stack.imgur.com/2Tbuc.png The cause of this problem has been somewhat identified, but the solution isn't clear without impacting the preview on computers. Here is th ...

When the Button is clicked, the component utilizing the Router fails to appear

My current task involves creating a page where users can choose between two options: Button 1 leads to TestOption.js, while Button 2 redirects to TestOption2 (currently using TestOption for testing purposes). The default landing page is SelectionPage. The ...

What could be causing the lack of responsiveness on this page?

I have created a webpage with over 1100 lines of code using JSF 2.0. The page is filled with PrimeFaces components and I have implemented JQuery to control the appearance and disappearance of these components. The webpage functions smoothly on Firefox 4.0 ...

Synchronizing Form Data in Angular 5: Pass and Populate Dropdowns between Components

I have developed a unique form (material dialog modal) that allows users to create an account. When the user clicks on the Register button, their created account should appear in a dropdown menu without redirecting or reloading the current page. I am facin ...

What is the best way to make a Modal triggered by a loop embedded within a table function properly on mobile devices?

While the modal is functioning properly on desktop, it seems to be encountering issues on mobile devices. The modal appears behind the background and is confined by the boundaries of the table (tbody). Below is the code snippet for triggering the modal: ...

Tips for sending two values to a PHP file using JavaScript Ajax

I have created a code for two dropdown menus. The goal is to select values from both menus and send them to a php file using the GET method. The values should be sent to the php file only when both menus have selections made. Below is the code snippet: ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

Exploring immersive virtual reality websites with a complete full-screen 3D experience

As I work on building a virtual reality website, I find myself pondering a challenging question: how can we seamlessly transition users from experiencing one VR website in full screen stereoscopic view to another, all without disrupting their immersive e ...

What is the process for using the fetch method in React to upload a file?

Currently, I am developing a react component that involves uploading an Excel file to a server. Although my approach seems correct, it returns an empty object when I check the request body in console. <input type="file" id="avatar" name="avatar" onChan ...

Setting a value in the selectpicker of rsuitejs involves assigning a specific value to the

const _DATA = [{ code: 'code1', name: 'Jagger' },{ code: 'code2', name: 'Tigger' },{ code: 'code3', name: 'Lion' }] <SelectPicker data={_DATA.map(x => {return {label: x.n ...

Struggling to capture an error generated by Sequelize within a universal Middleware block

In a test project, I have successfully implemented CLS transaction control in Sequelize using 'cls-hooked'. The transactions work seamlessly both in the command line and with Express. They are injected and managed automatically, rolling back on a ...

Accessing an object's property within a mapped array in a Next.js application is possible

Currently, I am attempting to iterate through an array of objects and extract the link property as a <li></li> element. However, I am facing an issue where nothing is being returned: import { useState, useEffect } from "react"; import ...

The styling of HTML elements is ineffective when using scoped styles

I'm facing an issue where my element styling doesn't seem to work when using the scoped attribute. Upon inspecting the element, it appears that the styling is not being applied when using scoped. The reason I need to use scoped is because I want ...