Can one echo the value of a variable within an array reference?

I am trying to extract the value of an input based on its class and then use that value in an associative array

Here is my current javascript code:

var phone_code = document.getElementsByClassName( 'model' ).value;
var phone = [];
phone["6s"] = "23.52";
phone["5s"] = "9.88";
phone["5Se"] = "14.59";
phone["7"] = "28.49";
phone["s7e"] = "27.49";
phone["s7"] = "23.52";
phone["s6e"] = "21.04";
phone["s6"] = "18.56";
phone["a5"] = "12.61";
phone["j5"] = "7.65";
phone["a3"] = "8.64";
phone["j3"] = "5.17";
phone["p9"] = "16.08";
phone["p9lite"] = "8.64";

document.getElementById("phone-cost").innerHTML = phone[phone_code]

The output from the array is as follows:

Your Phone would cost you £<span id="phone-cost"></span> per month

However, the output just shows "undefined," indicating there might be an issue with the javascript or elsewhere in the process.

The variable `phone_code` should be derived based on the enabled dropdown menu, but I suspect that the problem lies in how I am referencing it within the array.

phone[phone_code]

I am unsure if this is the correct way to reference the variable within an array structure, and I have not found a definitive answer on the proper format to use.

Any insights would be greatly appreciated. Thank you!

Answer №1

There are a couple of key points to note:

(1) The method .getElementsByClassName() will return an array-like object containing elements, not just a single element.
(2) Although it's feasible to work with arrays in your code as you're currently doing, it is actually more beneficial to utilize a plain object.

Take a look at the revised example below:

var btn = document.getElementById('getPrice');

btn.addEventListener('click', function() {
  var phone_code = document.getElementsByClassName('model')[0].value;

  var phone = {};
  phone["6s"] = "23.52";
  phone["5s"] = "9.88";
  phone["5Se"] = "14.59";
  phone["7"] = "28.49";
  phone["s7e"] = "27.49";
  phone["s7"] = "23.52";
  phone["s6e"] = "21.04";
  phone["s6"] = "18.56";
  phone["a5"] = "12.61";
  phone["j5"] = "7.65";
  phone["a3"] = "8.64";
  phone["j3"] = "5.17";
  phone["p9"] = "16.08";
  phone["p9lite"] = "8.64";

  document.getElementById("phone-cost").innerHTML = phone[phone_code];
});
<select class="model">
  <option value="6s">6s</option>
  <option value="5s">5s</option>
  <option value="5Se">5Se</option>
</select>
<input type="button" value="Get Price" id="getPrice" />Your Phone would cost you £<span id="phone-cost"></span> per month

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

Sorting rows in ag-grid based on custom data displayed by cellRenderer

My goal is to enable column sorting on cell data that includes custom HTML elements. I understand that I might need to create a custom function to override the default sorting behavior and refer it to the raw values instead of the rendered HTML output. De ...

Acquire information asynchronously in JavaScript while inside a for loop

Recently, I've been exploring this particular function snippet: function add_cnh(arr_clelem){ var id=arr_clelem.getElementsByClassName("present")[0].id; var date=arr_clelem.getElementsByClassName("present")[0].getAttribute('date'); v ...

Vue2: when passing a function as a prop, a warning will be triggered indicating that the prop has

As a newcomer to Vue, I've been enjoying working with Single File Components. Before diving into my main project idea, I decided to experiment with some small components to get a better grasp of the concept. One such experiment involved creating a co ...

Have you considered utilizing "call for('express')()" instead?

When creating a simple Web server with NodeJS and Express, most tutorials provide examples like the following: const express = require('express'); const app = express(); app.listen(3000, () => console.log("Started")) app.get(' ...

Is there a way to remove an individual file from an HTML file input field?

I recently took on the task of implementing a delete function for an HTML file input with the type "file". The goal is to delete a single file from a list of multiple files. While deleting all files at once is simple, I am having trouble with my function t ...

retrieve information at varying intervals through ajax

In my web page, there are two div elements that both fetch server data using AJAX. However, div-a retrieves data every second while div-b retrieves data every minute. How can I adjust the frequency at which each div fetches server data? ...

Command in Selenium Webdriver for initiating a mouse click

Currently, I am in the process of writing tests for a Java application that has been created with the Vaadin framework. To conduct these tests, I have opted to utilize the Robot Framework. In certain instances, I must implement robot framework commands suc ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

A step-by-step guide on displaying log files using NanoHTTPD

I have developed a Java desktop application that can receive HTTP requests using the embedded NanoHTTPD web server from https://github.com/NanoHttpd/nanohttpd. Once an HTTP request is received, my application performs certain tasks and logs the activity to ...

Easily ajaxify your website without the need for hash or hashbang URLs

Currently enrolled in a web design course, I am eager to explore the world of ajax and how it can enhance our projects. Unfortunately, our instructor focuses solely on design and HTML, leaving us to figure out the more technical aspects on our own. If I m ...

Utilize information stored in a database to automatically navigate to a different webpage

I am currently working with PHP, HTML, and a mySQL database. Here are my current project requirements: Retreive specific data from the database and output it. Compare this data with predetermined values. If the data falls outside of the specified range, ...

Firefox does not allow contenteditable elements to be edited if they are nested inside a parent element that is draggable

Here is a basic HTML example: <div draggable=true> <div contenteditable=true>can't edit me</div> </div> When testing in Chrome, I noticed that I was able to edit the contents of the contenteditable div, however, this functi ...

Having issues with Pubnub subscription functionality

Currently, I am in the process of incorporating a basic chat feature into my web application using AngularJs 1.4.5 and pubnub. To do this, I am following the instructions outlined in the pubnub tutorial. $scope.channel = 'chat_for_trial'; $scop ...

Issue with displaying Angular chart only resolves after resizing window following routing updates

Hey there! I'm having trouble getting my chart to show up after adding routing to my 3 tabs. Previously, without routing, everything worked fine. Now, the graph only appears after resizing the window. The chart is using PrimeNG chart with the Chart.js ...

What is causing the component to render three times?

Below is the structure of my component: import { useEffect, useState } from "react"; function Counter() { const [count, setCount] = useState(0); console.log("comp run"); const tick = () => { setCount(count + 1); conso ...

The API response appears to be a successful 200 status code, however the actual result is a

I'm currently working with a VUEJS / VUEJS Resources code snippet that retrieves data from an API service. fetchData: function(name){ var self = this; self.$http.get('http://www.apiservice.com/', { params: { ...

Rotating a path in Three.js: A beginner's guide

I am a beginner with three.js and I am trying to make an object move along an ellipse curve. However, when I rotate the ellipse using ellipse.rotation.y, the object no longer follows the path correctly. It continues to move along the original path instead. ...

The state value is not preserved after redirecting to another page

For the past couple of days, I've been struggling with an issue and I can't seem to figure out what I'm doing wrong. My goal is to create a login page that redirects users to the dashboard after they log in. To maintain consistency acros ...

What methods can I use to conceal #! from showing on the browser's address bar?

Imagine you have the below link: www.someurl.com/#!?page=index How would you convert it into one of these options: www.someurl.com/#!/index (using mod_rewrite) www.someurl.com/ajax/index (also using mod_rewrite, but replacing #! with ajax) www.someurl. ...

Defining a Global Variable using the jQuery $(this)

I have been looking for ways to simplify my coding process, and one method I've tried is assigning a global variable. var parent = $(this).parent().parent().parent(); var parentModule = $(this).parent().parent().parent().parent(); Throughout my code ...