Tips for extracting the chosen value from a select option dropdown and incorporating it into a switch statement

WHAT WORKS
Upon entering the 'monetary' value and clicking the 'calculate my taxes' button, you will receive the correct values.

WHAT DOESN'T WORK
An Issue to Address

The total tax amount is influenced by the duties category you choose.
1. By default, 'Electronics' is chosen and upon calculating the tax, the accurate value is displayed.
2. If you attempt to select a different duty category while using the same 'total amount', the tax amount shown does not change.
3. Even after refreshing and selecting an option other than electronics, the payment amount remains consistent for all 3 options (depending on the total amount entered.)

I extend my gratitude for your assistance in advance.
Here's the link to the repl: https://repl.it/@argo92/CUSTOMS-CALCULATOR

//Percentages based on duties category
const TAX_ELECTRONICS = 0.31 //31%
const TAX_AUTOMOBILES = 0.33 //33%
const TAX_PERISHABLES = 0.12 //12%

// Exhibit 1: Acquire and store value from select option
var selObj = document.getElementById("dutiesCategory");
var selValue = selObj.options[selObj.selectedIndex].value;

// Check Option Value click handler
function getOption() {
    selectElement = document.querySelector('#dutiesCategory');
    output = selectElement.value;
    document.querySelector('.output').textContent = output;
}
var e = getOption();

// Exhibit 2: Test to confirm if an option value is still retrieved
function tester() {
var f = $("#dutiesCategory").change(function() {
    var g = $(this).find("option:selected").val();
    console.log(g);
});
}
tester();

// An Important Note: I am seeking a method to extract values from the select input and integrate them with the calculateTax function.
function calcDutiesCatTax(val) {
    if (selValue) {
        return TAX_ELECTRONICS;
    } else if (selValue) {
        return TAX_PERISHABLES;
    } else {
        return TAX_AUTOMOBILES;
    }
};

    // function calcDutiesCatTax(val) {
    // var result = "";
    // switch (selValue === val) {
    //  case 'Electronics':
    //      result = TAX_ELECTRONICS;
    //      break;
    //  case 'Automobile':
    //      result = TAX_AUTOMOBILES;
    //      break;
    //  case 'Food':
    //      result = TAX_PERISHABLES;
    //      break;
    // }
    // return result;
    // }

// Tax calculation function
function calculateTax() {
    //TEST Government Compound taxes base num = 350
    var x = document.getElementById("totalAmount").value;
    var ITEM_COST = parseInt(x);
    var TAX_10 = ITEM_COST * 0.10; // 35
    var TAX_5 = ITEM_COST * 0.05; // 17.5
    var TAX_2 = ITEM_COST * 0.02; // 7
    var TAX_8 = ITEM_COST * 0.08; // 28
    var totalCompoundTax = TAX_10 + TAX_5 + TAX_2 + TAX_8;

    // Calculate tax based on category
    var feesFromDutiesCat = calcDutiesCatTax(e) * ITEM_COST;
    console.log(feesFromDutiesCat);
    // Total amount to be paid (Inclusive of all taxes)
    var totalAmountToBePaidInEc = feesFromDutiesCat + totalCompoundTax * (2.68);
    var totalAmountToBePaidInUsd = feesFromDutiesCat + totalCompoundTax;

    document.getElementById("totaltaxesXCD").innerHTML = totalAmountToBePaidInEc.toFixed(2) + ' XCD';
    document.getElementById("totaltaxesUSD").innerHTML = '$' + totalAmountToBePaidInUsd.toFixed(2);
}

// console.log(selValue);
// var calcDutiesCat = function (value) {
//  var result = "";
//  switch (value) {
//      case 'electronics':
//          result = TAX_ELECTRONICS;
//          break;
//      case 'Automobile':
//          result = TAX_AUTOMOBILES;
//          break;
//      case 'Food':
//          result = TAX_PERISHABLES;
//          break;
//  }
//  return result;
// }

// function calcDutiesCatTax(val) {
//      if (val === selValue) {
//          return TAX_ELECTRONICS;
//      } else if (val === selValue) {
//          return TAX_PERISHABLES;
//      } else {
//          return TAX_AUTOMOBILES;
//      }
//  }

Answer №1

Replacing the calcDutiesCatTax() function may be what you need for your solution.

//Percentages assigned to duties categories
const TAX_ELECTRONICS = 0.31 //31%
const TAX_AUTOMOBILES = 0.33 //33%
const TAX_PERISHABLES = 0.12 //12%

// Storing value from select option
var selObj = document.getElementById("dutiesCategory");
var selValue = selObj.options[selObj.selectedIndex].value;

// Check Option Value click handler
function getOption() {
selectElement = document.querySelector('#dutiesCategory');
output = selectElement.value;
document.querySelector('.output').textContent = output;
}
var e = getOption();

// Testing if options are still being received
function tester() {
var f = $("#dutiesCategory").change(function() {
var g = $(this).find("option:selected").val();
//console.log(g);
});
}
tester();

// Functionality to incorporate values from select input into calculateTax function
function calcDutiesCatTax() {

if($("#dutiesCategory").val() == "electronics")
{
return TAX_ELECTRONICS;
}
else if($("#dutiesCategory").val() == "food")
{
return TAX_PERISHABLES;
}
else if($("#dutiesCategory").val() == "automobile")
{
return TAX_AUTOMOBILES;
}

};

// Tax calculation function
function calculateTax() {
debugger
// Sample Government Compound taxes base amount = 350
var x = document.getElementById("totalAmount").value;
var ITEM_COST = parseInt(x);
var TAX_10 = ITEM_COST * 0.10; // 35
var TAX_5 = ITEM_COST * 0.05; // 17.5
var TAX_2 = ITEM_COST * 0.02; // 7
var TAX_8 = ITEM_COST * 0.08; // 28
var totalCompoundTax = TAX_10 + TAX_5 + TAX_2 + TAX_8;

// Calculate tax based on category
var feesFromDutiesCat = calcDutiesCatTax() * ITEM_COST;
console.log(feesFromDutiesCat);
// Total amount to be paid (Inclusive of all taxes)
var totalAmountToBePaidInEc = feesFromDutiesCat + totalCompoundTax * (2.68);
var totalAmountToBePaidInUsd = feesFromDutiesCat + totalCompoundTax;

document.getElementById("totaltaxesXCD").innerHTML = totalAmountToBePaidInEc.toFixed(2) + ' XCD';
document.getElementById("totaltaxesUSD").innerHTML = '$' + totalAmountToBePaidInUsd.toFixed(2);
}

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
.... (Additional HTML code truncated for brevity) ....
  </body>
</html>

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

Ajax RSS Feed - Weather Data from OpenWeatherMap

I am encountering an issue where the feed does not refresh with new news as they come in, even after selecting an option. This same problem is also occurring with openweather. I suspect that everything is being cached when it shouldn't be. Should I ch ...

Content that is dynamically generated by a database

I have been working on creating a unique wall feature for my website, inspired by Facebook. My aim is to allow users to submit form data and have it validated before storing it in a database. Additionally, I want this stored data to be displayed in a desig ...

Cannot chain promises using 'then'

Having trouble understanding why the 'describeDir' promise chain is not working properly. Can anyone help me figure out what I did wrong here? Everything in the code seems to run, but functions like then or finally from the promise API never get ...

Error Message: Unexpected character "C" found in JSON response from Ionic 2 Http GET request

Trying to execute a GET request and extract data from the response. this.http.get('http://localhost:8888/maneappback/more-items.php').subscribe(res => { console.log(res.json()); }, (err) => { console.log(err); }); An error message ...

What could be causing the remaining part of the template to not render when using an Angular directive?

After adding my custom directive to a template on an existing page, I noticed that only the directive was rendering and the rest of the template was not showing up as expected. Even though the controller seemed to have executed based on console logs and B ...

Show options via checkboxes

Looking to create a dynamic leaderboard for gym exercises, where users can select exercises from a database and have them appear as options in the navbar. Currently manually adding exercises, but seeking a more efficient solution using Bootstrap 5. Any tip ...

Despite my attempts to assign null as a value to the key named null, the result continues to be undefined

I created a custom parseJSON function that is intended to produce the same result as JSON.parse when given the same input. There's also a helper function named getParsed() that correctly parses strings into their respective data types. However, I&apos ...

Trying my hand at a Cascading Style Sheets jQuery Snake

I'm a beginner in the realm of Javascript, and I've recently tried my hand at creating a simple classic snake game. Instead of using complex graphics, I opted for a more HTML/CSS approach where each pixel on the map is represented by a div box, a ...

Switch Hidden Input Value When UserControl is in Focus

This task seems deceptively simple, but I'm encountering difficulties trying to make it happen. Within ResidentAddress.aspx, there are two user controls (AppName.ascx and NavButtons.ascx). My goal is to update a hidden input field on NavButtons.ascx ...

There was an error thrown: Unable to access properties of an undefined value (specifically trying to read 'first')

Yesterday, my sister requested me to add a language change button to her website for some text. However, upon implementing it, I encountered the following error: Uncaught TypeError: Cannot read properties of undefined (reading 'first'). Despite t ...

Resetting ajax success message when modal is closed

Currently utilizing w3.css and its modal feature, I am encountering an issue with clearing the message displayed after a successful ajax call once the window is closed. Even though I have implemented code to clear the message upon closing the window (by cl ...

Component receiving undefined response from Angular service

I am having trouble passing the return value to my component. I have a service set up using firebase, but when I call the getLoggedInUser method in my component, it returns undefined. I need help figuring out how to pass the doc.id to my component from my ...

I am experiencing an issue where jQuery is not functioning properly within my Groovy Server Page

In my Groovy Server Page, I am struggling with a jQuery function that is not running as expected. When my controller's function renders an error message, it appears on the "next" web page instead of on the same page using Ajax. I double-checked that j ...

Guide to displaying or hiding elements based on the number of selected checkboxes

When only one checkbox is checked, all buttons in the head-btn class should be displayed. By default, only the add folder and upload buttons are shown. If a user selects two checkboxes, the share button should be hidden. If they uncheck one of the checkbo ...

What is the method for placing a title in the initial column with the help of v-simple-table from Vuetify.js?

I am interested in using the v-simple-table UI component from Vuetify.js to create a table similar to the one shown below. https://i.sstatic.net/QNdpJ.png After creating the code in codesandbox and previewing the output, I noticed that the title is not a ...

Trigger a notification from one webpage to another (PHP, JavaScript, HTML)

I'm currently working on a website that consists of both a receptionist page and a user page with multiple logins. The receptionist page displays a table listing all logged-in users, including their status (either ready or busy). This table is refresh ...

Angularfire: how synchronized arrays behave

Recently, I've encountered some issues with synchronized arrays in AngularJS using AngularFire. My setup includes angularfire 1.1.3 and firebase 2.3.1. I initialized the query like this: var arr = $firebaseArray(ref.limitToFirst(5)); Initially, when ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

I am facing an issue with Lotties having a black background in my NextJS project. Is there a way to make them transparent

I am facing an issue with my LottieFiles (JSON) displaying a black background when imported into my NextJS project. Despite trying to set background='transparent' on both the Player and parent div, the problem persists. I made sure to export my ...

Updating the state of a Next.JS router component with React.JS: A step-by-step guide

I've implemented a toggleswitch in my app that changes its state based on the dynamic URL parameters. For instance, if the URL includes a parameter named followType set to following (e.g. https://www.example.com/home?followType=following), I want the ...