Struggling to determine the expense upon button activation - data remains stagnant

My coding project involves a basic ordering system where users can input an integer, click on an update button, and see the total cost displayed below. Despite my efforts, I've encountered issues with two different methods:

  1. Using plain JavaScript for orderQuantity - innerHTML fails to update
  2. Using parseInt for orderQuantity - innerHTML returns £NaN

I need some guidance in identifying where the problem lies. Here's the code snippet:

let orderQuantity = parseInt(document.getElementById("order-stepper").value);
let orderText = document.getElementById("order-value");
let orderValue = 2.50;
let orderAmount =  orderValue * orderQuantity;
let updateButton = document.getElementById("order-update");

function update() {
  orderText.innerHTML = ("Total cost: £" + orderAmount);
}

updateButton.addEventListener("click", update);
.order-stepper {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
...
... (CSS styles omitted for brevity)
...
#order-update:hover {
  background-color: #e2979c;
}
<div class="order-stepper">
          <label for="quantity">Select your quantity</label>
          <input id="order-stepper" type="number" name="quantity" value="" max="3">
        </div>
        <button id="order-update" type="button" name="button">Update</button>
        <div class="order-price">
          <h2 id="order-value">Total cost: £0</h2>
        </div>

If anyone can provide assistance, it would be greatly appreciated.

Answer №1

It is recommended to move the variables inside the function for better performance. The current setup initializes the variables only once and does not update them with the changing value of the text box, resulting in no value being displayed when the update button is clicked.

let updateButton = document.getElementById("order-update");

function update() {
    let orderQuantity = parseInt(document.getElementById("order-stepper").value);
    let orderText = document.getElementById("order-value");
    let orderValue = 2.50;
    let orderAmount =  orderValue * orderQuantity;

  orderText.innerHTML = ("Total cost: £" + orderAmount);
}

updateButton.addEventListener("click", update);
.order-stepper {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.order-stepper label {
  font-size: 20px;
  margin: 30px 20px;
}

.order-stepper input {
  font-size: 18px;
  background-color: #f9f9f9;
  color: #999;
}

.order-price {
  width: 80%;
  display: flex;
  align-items: center;
  justify-content: center;
}

#order-value {
  font-size: 28px;
}

#order-update {
  height: 60px;
  width: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 30px 0;
  border: 3px solid #e2979c;
  border-radius: 5px;
  font-size: 2rem;
  font-weight: bold;
  background-color: #fff;
  cursor: pointer;
}

#order-update:hover {
  background-color: #e2979c;
}
<div class="order-stepper">
  <label for="quantity">Select your quantity</label>
  <input id="order-stepper" type="number" name="quantity" value="" max="3">
</div>
<button id="order-update" type="button" name="button">Update</button>
<div class="order-price">
  <h2 id="order-value">Total cost: £0</h2>
</div>

Answer №2

It's a good idea to include variables inside the function for a cleaner and safer code. One way to improve it is by using const instead of let, employing the shorthand + for parseInt(), and using element.textContent for security rather than element.innerHTML.

document.getElementById("order-update").addEventListener("click", update);

function update() {
    const orderQuantity = +document.getElementById("order-stepper").value;
    const orderText = document.getElementById("order-value");
    const orderValue = 2.50;
    const orderAmount = orderValue * orderQuantity;
    orderText.textContent = ("Total cost: £" + orderAmount);
}

Furthermore, when importing the JS file in the head section, remember to use the defer attribute to prevent any issues with your listener.

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="app.css">
    <script src="app.js" defer></script>
</head>

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

Guide on Triggering a Custom Popup Message upon a Server Action in Next.js

Hey there, I'm currently facing some difficulties in finding the proper way to trigger a toast notification after successfully mutating data using server actions in Nextjs 13. The toast component I'm working with is specifically designed for clie ...

Preventing access to websites through a web application using JavaScript

I am in the process of creating a web application that enables users to create a list of websites they wish to block, preventing access from their browsers. My goal is to block websites on all browsers, but I have narrowed my focus to Chrome for now. I ha ...

Zoom in and Zoom out functions in ngPdf with centered view

I have incorporated the pdf canvas to showcase PDFs on my AngularJS/Bootstrap application, and I must say, the preview feature is working exceptionally well. However, one thing that I would like to achieve is centering either my modal or the canvas itself ...

Unlocking the Power of Combining JMVC and Server-side MVC Models

It's been a few days since I posted this question here and still no response. I also tried posting it on forum.javascriptMVC.com and finally got an answer, but I'm looking for more insights. Here's my question: After reading the documentat ...

moodle - eliminate the need for grading at the same time

I'm currently setting up a Moodle installation and I'm looking for suggestions on how to prevent simultaneous grading. My goal is to have several evaluators grading students across various courses without any conflicts. If you have any recommend ...

The script tags encountered an issue loading the resource with a status code of 404

Currently working on an ASP.NET MVC project and encountered an issue on one of the pages. Here is the code snippet with a script included at the bottom... @model IEnumerable<PixelBox.Dtos.ItemGetDto> @{ ViewBag.Title = "Index"; } <body> ...

Utilizing one JavaScript file and consistent classes for multiple modals

Is it possible to have multiple modals using the same JS file, classes, and IDs? I created this code: <button id='myBtn'>Order/Discount</button> <div id='myModal' class='modal'> <div clas ...

Unable to access frame: Error - Unable to retrieve 'add' property from undefined

I am working on customizing the chatbot functionality for my website built with Nuxt.js. I want the chatbot to display on certain pages while remaining hidden on others. Unfortunately, I encountered an issue when trying to hide it on specific pages. To im ...

Expressing the assignment of arrays inside the req.body object to separate variables

I've been facing some challenges trying to get Express and body-parser to properly interpret the JSON object sent from the Angular side of my app. It seems like there might be an issue with how I'm assigning variables in my syntax. Despite trying ...

Locate a specific data point within an array of JSON objects

After receiving an array of JSON objects from JSP, I now have a set of data that contains book titles. "Titles":[ { "Book3" : "BULLETIN 3" } , { "Book1" : "BULLETIN 1" } , { "Book2" : "B ...

Increment and decrement the like count on fa-heart multiple times

Is there a way to increment the count of a fa-heart value on click and decrement it on the second click? The issue I'm facing is that I have multiple fa-heart elements on the same page, making it challenging to increment or decrement the clicked fa-h ...

Unable to vertically scroll on a position fixed element

I recently created a unique VueJS component that enables vertical scrolling. Within this component, there are two elements each with a height of 100vh. At the bottom of the component is a fixed position div. Interestingly, when I try to scroll down using m ...

The click event will not be triggered if the element is removed by my blur event

My dropdown list is dynamic, with clickable items that trigger actions when clicked. Upon focus, the list displays suggested items When blurred, the list clears its contents The issue arises when blur/focusout events are triggered, causing my element to ...

What reasons could be preventing the state from updating correctly in Vuex?

Currently, I am working on a project where I am utilizing vuex along with axios to retrieve data from the backend. The issue arises when I try to access the state - even though the updated state is displayed successfully when I console-log it, there seems ...

Original selection unavailable in pagination

I'm encountering an issue on my website where Bootstrap and JQuery don't seem to work well together. $("ul.pagination li:not(.active) a").on("click",function(){ $(".pagination li.active").removeClass("active"); $(this).parent().addClass("activ ...

How can you implement a bootstrap navigation bar in a vue.js project?

I have encountered a problem with using html in my vue project. Despite following the documentation, it seems that the html is not working properly. I am unsure if this issue could be related to the import of popper.js. I have checked my code and I believe ...

Initiating the onclick event for Input/Form

<form method="POST" onsubmit="return false;"> ... <input type="submit" name="button" value="Login" onclick="require('file.js').submitForm(this.form);"> ... </form> Is there a way to trigger the onclick event of this INPUT eleme ...

JavaScript Popup Box Failing to Trigger

Snippet of Code: <form method="post" id="cp_ind_form"> // several input fields here... <input type="submit" name="update_submit" value="Update" /> <input type="submit" name="delete_submit" value="Delete" onclick="deleteConfi ...

Issue with applying Angular animation to child element

Here I have set up two different animations. animations: [ trigger('fadeIn', [ transition('void => *', [ style({opacity: 0}), animate(500), ]), ]), trigger('fallIn',[ transition ...

Obtaining the node generated from a document fragment

Suppose I add a document fragment to the DOM in the following way: const ul = document.querySelector("ul"); const fruits = ["Apple", "Orange", "Banana", "Melon"]; const fragment = new DocumentFragment(); ...