Ways to attribute a numeric worth to a choice in a JavaScript form

I am in the process of creating a form that allows users to customize and order pizza while showing them the invoice as they make their selections.

Currently, I have successfully implemented the display of user-selected options, but I am struggling with adding prices to these choices. My goal is to set prices for different sizes and toppings (both regular and premium) as the user selects them. Additionally, I encounter an issue where the invoice is only generated if the sizeOfPizza function is present on its own, and adding other JavaScript functions causes it to malfunction.

//function to show selected pizza size
function sizeOfPizza(size) {
  document.getElementById("pizzaSize").value = size;
}

//function to determine price based on size selection 
function determineSizePrice(size) {
  
  if (size == "Personal") {
    var pizzaSizePrice = 5;

  } else if (size == "Medium") {
    var pizzaSizePrice = 8;

  } else if (size == "Large") {
    var pizzaSizePrice = 10;

  } else if (size == "Extra Large") {
    var pizzaSizePrice = 12;

  } else if (size == "Holy Pizza") {
    var pizzaSizePrice = 20;

  }
  document.getElementById("pizzaSizePrice").value = pizzaSizePrice; 

}
<h3> Select Size </h3>

<form id="pizza-size">
  <input type="radio" name="size" onclick="sizeOfPizza(this.value)" value="Personal"> Personal (4 Slices) <br>
  <input type="radio" name="size" onclick="sizeOfPizza(this.value)" value="Medium"> Medium (8 slices)<br>
  <input type="radio" name="size" onclick="sizeOfPizza(this.value)" value="Large"> Large (10 slices) <br>
  <input type="radio" name="size" onclick="sizeOfPizza(this.value)" value="Extra Large"> Extra Large (12 slices)<br>
  <input type="radio" name="size" onclick="sizeOfPizza(this.value)" value="Holy Pizza"> Holy Pizza Batman (24 slices) <br>
</form>
<br>


<br> Pizza Size: <output id="pizzaSize"> </output> <br> Pizza Size Price: <output id="pizzaSizePrice">
    
    <br>

Answer №1

Consider following these improved guidelines:

It seems that your script contained spelling errors in the "Personal" section (should be lowercase), as well as a missing </output> tag and other issues.

const prices = {
  "Personal": 5,
  "Medium": 8,
  "Large": 10,
  "Extra Large": 12,
  "Holy Pizza": 20
}

window.addEventListener("load", function() { // when page loads
  document.getElementById("pizza-size").addEventListener("click", function(e) { // pass the event  - in this case the click event
    var tgt = e.target; // what was clicked
    if (tgt.name === "size") { // is it one of the radios?
      var val = tgt.value; // save the value once (DRY principle)
      document.getElementById("pizzaSize").value = val;
      document.getElementById("pizzaSizePrice").value = prices[val]; // look up the price in the prices object
    }
  })
})
<h3> Select Size </h3>
<form id="pizza-size">
  <input type="radio" name="size" value="Personal"> Personal (4 Slices) <br>
  <input type="radio" name="size" value="Medium"> Medium (8 slices)<br>
  <input type="radio" name="size" value="Large"> Large (10 slices) <br>
  <input type="radio" name="size" value="Extra Large"> Extra Large (12 slices)<br>
  <input type="radio" name="size" value="Holy Pizza"> Holy Pizza Batman (24 slices) <br>
</form><hr/>
Pizza Size: <output id="pizzaSize"> </output> <br> 
Pizza Size Price: <output id="pizzaSizePrice"></output>
    

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

Is it possible to configure npm install to install "bin" executables directly into the local node_modules directory (rather than the .bin directory)?

In my Node project, I am able to package it into a tarball using npm pack, and then install it in another directory for testing purposes. This allows the files specified in the "bin" section of my package.json file to be symlinked correctly into the node_m ...

Unable to retrieve the second number enclosed in parentheses using regular expressions

Currently, I am diving into the world of regex and encountering a set of strings formatted as "(9/13)". My goal is to retrieve the second number in this format. To achieve this, I experimented with the following regex pattern: /\(.*?[^\d]*(\ ...

Unable to update content within the `style` attribute when the HTML is stored in a variable

I am attempting to make changes to the style html - specifically by replacing a string, but unfortunately it is not functioning as expected. I am struggling to obtain the final updated html. Below is my attempt: var html = "<style>043BF83A8FB24A418 ...

Deploying an Express.js application: The command 'PassengerAppRoot' is invalid, possibly due to a misspelling or being defined by a module not included in the server configuration

I am looking to host an express.js app on cPanel. After successfully installing node, nvm, and npm, I managed to upload all the necessary files to the server and configure the .htaccess file. However, despite my efforts, cPanel's error logs are still ...

Is it possible to refresh text in table without clearing icons?

Is there a way to maintain icons in table rows when editing text fields from a dialog? Currently, regardless of whether I use .html() or .text(), the icons disappear. I suspect that utilizing .content() may be a solution, but I'm unsure how to impleme ...

Trouble with Firebase/Firestore documentation queries in JavaScript

Having trouble using the new Firestore system. I'm trying to retrieve a Collection of all users and go through it, but I can't seem to make it work. db.collection("users").get().then(function(querySnapshot){ console.log(querySnapshot.dat ...

JavaScript Paint Brush Tool Powered by HTML5

I am looking to create a smooth and clean opacity brush. Here is an example of the drawing line I want: This is the second picture I managed to achieve: When I move the cursor quickly, there are fewer circles in the drawing line. ...

Passport Node: Issue with Password Comparison results in an undefined function error, causing return done(null, user) to fail

I have reviewed all the relevant inquiries and responses but I am still unable to resolve this issue. Please see the code provided below and assist me in understanding why the terminal is displaying 'undefined is not a function'. Here is an overv ...

Build a dynamic table by leveraging JSON with the power of JavaScript and HTML

I'm currently working on creating a table where information is stored and updated (not appended) in a JSON file using JavaScript and HTML. The structure of my JSON data looks like this: [{ "A": { "name": "MAK", "height": 170, ...

Using jQuery .animate() leading to erratic input movements

I am currently utilizing jQuery's .animate() feature to create a smooth animation effect on the width of a <div> element when a child <input> is in focus. Nevertheless, I'm encountering an issue where the input field jumps up and down ...

Is using debounce with $scope.$apply a logical choice?

In my experience, I have come across a method that claims to decrease the number of $digest loops by incorporating debouncing into the $scope.$apply process. It looks something like this: $scope.$apply = _.debounce($scope.$apply, 250); Is this approach v ...

Dealing with lag in Kendo Grid (Utilizing Kendo Grid, Angular JS, and Web API)

Query : I have integrated a Kendo Grid into my Angular JS HTML page. The data for the Kendo Grid is fetched from a remote service Web API. While paging through the Kendo Grid, it attempts to download a whopping 38 MB of content for every 10 records, taki ...

jquery toggle for partial visibility not functioning properly

Can jquery sliding functions be used to partially show and hide content? In this scenario, there is a list with 7 items but only the first two are visible initially, while the rest are hidden. The goal is to have all 7 items show when the user clicks to v ...

The error message "TypeError ".deploy" is not a function in your Hardhat environment."

Currently, I'm in the process of developing a page for minting NFTs called astro-mint. To move forward, I need to deploy my contract using hardhat. However, when I execute this command npx hardhat run scripts/deploy.js --network dexitTestnet An erro ...

Executing a JS function within a table cell

I've been attempting to invoke a function within a table cell to dynamically create some data, but I keep encountering this error below. I'm uncertain whether I'm correctly calling defined functions and JavaScript functions inside the table ...

the mobile website is not properly aligned on a horizontal axis

As I work on creating a mobile version of my website, I've come across a challenge: The entire site fits perfectly on the computer at a browser width of 480px, but when viewed on my mobile phone (regardless of the browser used), it leaves space on the ...

Troubleshooting React-Redux: Button click not triggering action dispatch

I am facing an issue where my action is not being dispatched on button click. I have checked all the relevant files including action, reducer, root reducer, configStore, Index, and Component to find the problem. If anyone can help me troubleshoot why my a ...

JavaScript encountering a NaN value

I'm encountering an issue where I am receiving a NaN when attempting to summarize columns of a report. Additionally, my query is only retrieving 1 row of data, but the grid is displaying 2 rows. Does anyone have any suggestions on how to resolve this ...

Issue with $_SERVER['PHP_SELF'] not functioning properly

Apologies if this question has been asked before, but after searching extensively I couldn't find a solution. Therefore, I am posting here... The issue is that I'm trying to submit values on the same page (using jQuery Mobile UI) and I have used ...

communication flow in two directions between server and client

Looking for recommendations on a javascript/nodejs solution that enables bi-directional communication between server and client. The application flow involves the client sending a discovery service to the server, which responds with a challenge. The client ...