Inquiring about how to retrieve data from a table using option select drop-downs

I have a pricing table that is dependent on specific criteria, and I am familiar with using HTML tags for this purpose. I am interested in finding the most efficient way to retrieve the cost per square foot based on three dropdown box selections. These selections would be similar to the code snippet provided below.

<td> <select id="box1" oninput="calculate()">
<option value="0">Select Glass Pattern</option>
<option value="1">Autumn Leaves</option>
<option value="2">Treebark</option>
</select></td>

 <td> <select id="box2" oninput="calculate()">
<option value="0">Select Glass Thickness</option>
<option value="4">5/32 (4mm)</option>
<option value="10">3/8 (10mm)</option>
</select></td>

<td> <select id="box3" oninput="calculate()">
<option value="0">Select Glass Type</option>
<option value="1">Tempered</option>
<option value="2">Annealed</option>
</select></td>

I am seeking guidance on how to efficiently retrieve the cost from the given table. For example, if I select Tempered Autumn Leaves in 5/32 thickness from the dropdown boxes, I want to be able to retrieve the square foot cost of $27, whereas I would get $17 for the annealed option.

Select Glass    Select Thickness    Tempered or Annealed?   Cost
Autumn Leaves      5/32(4mm)              Tempered         $27.00
Autumn Leaves      5/32(4mm)              Annealed         $17.00
Treebark           5/32(4mm)              Tempered         $31.00
Treebark           5/32(4mm)              Annealed         $19.00

Answer №1

<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Titel</title>
  </head>
  <body>
        <select id="box1" onchange="calculate()">
            <option value="">Select Glass Pattern</option>
            <option value="0">Autumn Leaves</option>
            <option value="1">Treebark</option>
        </select>
        <br>
        <select id="box2" onchange="calculate()">
            <option value="">Select Glass Thickness</option>
            <option value="0">5/32 (4mm)</option>
            <option value="1">3/8 (10mm)</option>
        </select>
        <br>
        <select id="box3" onchange="calculate()">
            <option value="">Select Glass Type</option>
            <option value="0">Tempered</option>
            <option value="1">Annealed</option>
        </select>
        <div id="output">Please select all three values</div>
        </div>
        <script>

            let calculate = () => {
                let box1_selection = getValueById("box1");
                let box2_selection = getValueById("box2");
                let box3_selection = getValueById("box3");

                if(box1_selection == "" || box2_selection == "" || box3_selection == "") {
                    document.getElementById("output").innerHTML = "Please select all three values";
                } else {
                    let value = "not specified";

                    /*if(box2_selection == 0 && box3_selection == 0 {
                        value = "$27.00";
                    } else if(box2_selection == 0 && box3_selection == 1) {
                        value = "$17.00";
                    }*/
                    value = getPrice(box1_selection, box2_selection, box3_selection);

                    document.getElementById("output").innerHTML = value;
                }
            }

            let getValueById = (id) => {
                let selection = document.getElementById(id);
                return selection.options[selection.selectedIndex].value;
            }

            let getPrice = (value_1, value_2, value_3) => {
                // price_data is a 3 dimensional array.
                let price_data = [
                    [
                        ["$27.00", "$17.00"],
                        ["not specified", "not specified"]
                    ],
                    [
                        ["$27.00", "$17.00"],
                        ["not specified", "not specified"]
                    ]
                ];
                return price_data[value_1][value_2][value_3];
            }
        </script>
  </body>
</html>

This addresses your query. Remember to use onselect instead of oninput and ensure that IDs are unique. Each selection should have unique values for options. Check out the example above to see the calculation based on the values provided in your table. You can further expand the calculate function for additional combinations. The importance of the first selection's value may vary, and the second selection may influence the final price.

edit: This version offers you the option to either calculate the price using the function or the if-else construct. The getPrice function utilizes a 3-dimensional array where each dimension corresponds to the values in box1, box2, and box3 respectively. Think of these dimensions as paths leading to your specified price. The if-else part is included for your convenience. I've also extracted code to retrieve the value of an HTML selection. If you have specific inquiries, feel free to ask.

Answer №2

To start off, ensure that each of your <option> elements have distinct value attributes for easy identification. It's a good practice to leave the 'selection' default with an empty string, and assign unique identifiers to the other selections.

Next, determine the selected value by using

element.options[element.selectedIndex].value
. In order to do this, you'll first need to obtain the element using document.getElementById(). Remember to place this logic inside the function because the value will change!

Lastly, verify that none of the three values are empty strings, indicating that selections have been made. In this example, I've simply displayed the entered values, but feel free to perform any necessary calculations.

For the Tempered / Annealed values, it's advisable to work with raw integers, but I've used strings in the example below to showcase output clarity:

function calculate() {
  var box1 = document.getElementById("box1");
  box1_value = box1.options[box1.selectedIndex].value;

  var box2 = document.getElementById("box2");
  box2_value = box2.options[box2.selectedIndex].value;

  var box3 = document.getElementById("box3");
  box3_value = box3.options[box3.selectedIndex].value;

  console.clear(); // Reset the output
  
  if (box1_value != "" && box2_value != "" && box3_value != "") {
    console.log(box1_value, box2_value, box3_value);
  }
}
<td>
  <select id="box1" oninput="calculate()">
    <option value="">Select Glass Pattern</option>
    <option value="Autumn Leaves">Autumn Leaves</option>
    <option value="Treebark">Treebark</option>
  </select>
</td>

<td>
  <select id="box2" oninput="calculate()">
    <option value="">Select Glass Thickness</option>
    <option value="5/32 (4mm)">5/32 (4mm)</option>
    <option value="3/8 (10mm)">3/8 (10mm)</option>
  </select>
</td>

<td>
  <select id="box3" oninput="calculate()">
    <option value="">Select Glass Type</option>
    <option value="Tempered - $27">Tempered</option>
    <option value="Annealed - $17">Annealed</option>
  </select>
</td>

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

When attempting to incorporate a video using Sencha, an error occurs stating that the resource is being interpreted as an image but is being

While attempting to incorporate a sample into Sencha, I encountered an error stating "Resource interpreted as Image but transferred with MIME type text/css". Ext.define('MyApp.view.Newpage', { extend: 'Ext.Video', xtype: ' ...

Having trouble triggering a click event with React testing library?

I am working with a <Select/> component as shown in the image below. https://i.sstatic.net/ko8Y0.png App.tsx import React, { useState, ChangeEvent } from "react"; import MySelect from "./MySelect"; export default function App ...

Tips for receiving live updates of active users online with the help of Mongoose and socket.io

I have been working on developing an app that covers various topics. Each topic has online users, and I am using express/socket.io/mongoose for the backend and flutter for the frontend. Currently, I am facing a challenge in displaying real-time informatio ...

Unspecified data transfer between child and parent components

I'm working on implementing a file selection feature in my child component, but I'm facing difficulties passing the selected file to the parent component. I'm struggling to find a solution for this issue and would appreciate some guidance. W ...

Can functions be used as keys in a collection in JavaScript's map?

Using functions as keys in JavaScript can be tricky because for js objects, functions are converted to their "toString" form. This poses a problem if two functions have the same body. var a = function() {}; var b = function() {}; var obj={}; obj[a] = 1; o ...

Error encountered in amCharts Serial Chart when data parsing is enabled with the setting "parseDates": true which resulted in the failure to display data

Using Spring as a webservice, I received a JSON response with stock data: [ { "date": "2016-04-17", "open": 1085.0, "high": 1092.2, "low": 1072.0, "close": 1088.3, "volume": 54100, "value": 1088.3 }, { "date": "2016-04-14", "open": 1081. ...

Position of JSON data response is inaccurate

Currently, I have a function that calls an API from the server in the following manner: getDataSet(callback) { request.open('POST', `${apiPath}`); request.setRequestHeader('Content-Type', 'application/x-ww ...

Updating the ID's of nested elements in JavaScript when duplicating an element

After a fruitless search on Google, I have turned to the experts on SO for assistance. The challenge: Create a duplicate of a dropdown menu and an input field with the click of a button (which can be done multiple times) The proposed solution: Implement ...

Discovering the minimum and maximum within an array containing objects

I am working with an array of objects that contain latitude and longitude points: var pts = [ { "X": 52.67528921580262, "Y": 8.373513221740723 }, { "X": 52.6759657545252, "Y": 8.374114036560059 }, { "X": 52.682574466310314, "Y": 8.372569084 ...

A guide on setting the array value on the user interface based on a key within the SectionList

My code is currently retrieving an array value and populating these values based on the key in a SectionList. The keys are displaying properly in the UI, but I am encountering some issues in my render item function, particularly in the second section. Esse ...

I have a vision of creating a unique Countdown Stopwatch that meets all my

I'm looking to create a custom countdown stopwatch where I can set the time and watch it count down to 0:00. The stopwatch should have three buttons: Start, Stop, and Reset. I've searched multiple websites for what I need but haven't found ...

Text flickering unexpectedly during hover animation in Bootstrap

Encountered a peculiar issue where dark colors flicker during animation. Link to codepen Adding -webkit-backface-visibility: hidden partially resolves the problem, but it also affects font appearance by making it tighter and brighter. This issue is obser ...

Checkbox fails to display as checked

I am currently working on implementing checkbox inputs in React JS. I have encountered an issue where the checkboxes do not visually show as checked when clicked, but I am still able to retrieve the value of the checkbox. Here is my code: Simple Checkbox I ...

Fixing extended properties on an express request can be done by following these steps

I've been working on a JavaScript middleware where I can extract user information using the "req" object in the route handler. When I log currentUser, I get the expected value, but I'm encountering a TypeScript error warning: Property 'curre ...

Learn how to implement icons within Textfield components using Material-UI and TypeScript in React

I have successfully created a form with validation using TypeScript Material UI and Formik. Now, I am looking to enhance the visual appeal by adding a material UI Icon within the textfield area. Below is a snippet of my code: import React from 'reac ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

The content division does not have a set position

The content div is not adapting to different screen sizes properly. As the width and height of the browser shrink, it's overlapping with the header and footer. I'm using flex but I'm unsure if I'm implementing it correctly. display: ...

invoking a function through prototype

<script> var Nancy = function(){ this.name = 'nancy' } Nancy.prototype.getNancy = function(){ alert(this.name); } Nancy.prototype.getNancy(); function Bob(){ ...

The CSS overflow property does not seem to be functioning properly when applied to a span element that

Here is my current setup: http://jsfiddle.net/YKXUb/1/ My CSS looks like this: .two { height: 100%; width: 100%; border:1px solid green; } .hold { float: left; height: 100%; width: 35%; border:1px solid green; } .right { hei ...

Implementing JavaScript alerts with the Internet Explorer WebDriver and Selenium

Currently, I am facing a challenge with a Java based application where I need to click on a cancel button. I am using IE Driver, Eclipse IDE, and my application only supports IE. [I am scripting in Java] Here is the scenario: Login to the application An ...