Determine the output by applying a constant value to the input

I'm having an issue with a loop function. The goal of the code is to allow users to enter a quantity of goods they want to buy, and then JavaScript calculates a fixed value based on the chosen quantity, which should be printed out. This functionality should work within an HTML table with multiple columns.

With the help of some forum members, I have managed to write most of the code, but I'm struggling with implementing a loop function.

Below is the complete code, where I've used paragraphs to highlight the relevant sections of the code.

Thank you for your assistance!

<?php
    session_start();
?>

<!DOCTYPE html>
<html style="font-size: 16px;">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <meta name="page_type" content="np-template-header-footer-from-plugin">
    <title>Riesenhuber</title>
    <link rel="stylesheet" href="nicepage.css" media="screen">
<link rel="stylesheet" href="Riesenhuber.css" media="screen">
    <script class="u-script" type="text/javascript" src="jquery.js" defer=""></script>
    <script class="u-script" type="text/javascript" src="nicepage.js" defer=""></script>
    <meta name="generator" content="Nicepage 3.26.0, nicepage.com">
    <link id="u-theme-google-font" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i|Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i">
    
    
    <script type="application/ld+json">{
        "@context": "http://schema.org",
        "@type": "Organization",
        "name": "Kulinarik"
    }</script>
    
    
    
    
    
    
    
    

    <script>
      document.querySelectorAll('.u-table-cell').forEach(item => {
        item.addEventListener('click', event => {
          (function() {
                          const basePrice = document.getElementById("basePrice");
                          const quantityInput = document.getElementById("quantity");
                          const resOutput = document.getElementById("field_sum");
                          quantityInput.addEventListener("change", function() {
                            let currentQuantity = parseFloat(quantityInput.value);
                            let currentBasePrice = parseFloat(basePrice.getAttribute("value"));
                            resOutput.textContent = currentQuantity * currentBasePrice;
                          });
                        })()
          })
        })
    </script>
    
    
    
    
    

    <meta name="theme-color" content="#478ac9">
    <meta property="og:title" content="Riesenhuber">
    <meta property="og:description" content="">
    <meta property="og:type" content="website">
  </head>
  <body class="u-body"><header class="u-clearfix u-grey-5 u-header u-sticky u-header" id="sec-d5e7"><div class="u-align-left u-clearfix u-sheet u-sheet-1">
        <nav class="u-menu u-menu-dropdown u-offcanvas u-menu-1">
          <div class="menu-collapse" style="font-size: 1rem; letter-spacing: 0px; font-weight: 700;">
            <a class="u-button-style u-custom-active-border-color u-custom-border u-custom-border-color u-custom-borders u-custom-hover-border-color u-custom-left-right-menu-spacing u-custom-padding-bottom u-custom-text-active-color u-custom-text-color u-custom-text-hover-color u-custom-top-bottom-menu-spacing u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" href="#">
              <svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#menu-hamburger"></use></svg>
              <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><symbol id="menu-hamburger" viewBox="0 0 16 16" style="width: 16px; height: 16px;"><rect y="1" width="16" height="2"></rect><rect y="7" width="16" height="2"></rect><rect y="13" width="16" height="2"></rect>
</symbol>
</defs></svg>
            </a>
          </div>
          <div class="u-custom-menu u-nav-container">
            <ul class="u-nav u-spacing-20 u-unstyled u-nav-1"><li class="u-nav-item"><a class="u-border-active-palette-1-base u-border-hover-palette-1-base u-button-style u-nav-link u-text-active-custom-color-1 u-text-grey-90 u-text-hover-palette-2-base" href="Startseite.html" style="padding: 10px;">Startseite</a>
</li><li class="u-nav-item"><a class="u-border-active-palette-1-base u-border-hover-palette-1-base u-button-style u-nav-link u-text-active-custom-col...

Answer №1

Check out the solution below:

<tr style="height: 55px;">
  <b>
                        <td class="u-table-cell u-table-cell-1"><b>Product</b><span style="font-weight: 700;"></span>
  </td>
  <td class="u-table-cell"></td>
  <td class="u-table-cell u-table-cell-3"><b>Unit Price</b></td>
  <td class="u-table-cell u-table-cell-4"><b>Quantity</b></td>
  <td class="u-table-cell u-table-cell-5"><b>Total Price</b></td>
  </b>
</tr>
<tr style="height: 55px;">
  <td class="u-table-cell">Corn Roll</td>
  <td class="u-table-cell"></td>
  <td class="u-table-cell">
    <p value="1.39" id="basePrice">1.39 €</p>
  </td>
  <td class="u-table-cell">
    <form id="Quantity">
      <input type="number" min="0" id="quantity" value="0" step="1.0">
    </form>
  </td>
  <td class="u-table-cell">
    <form id="sum">
      <p><output id="field_sum" for="quantity">0</output> €</p>
    </form>
  </td>
</tr>
<script>
(function() {
  const basePrice = document.getElementById("basePrice");
  const quantityInput = document.getElementById("quantity");
  const resOutput = document.getElementById("field_sum");
  quantityInput.addEventListener("change", function() {
    let currentQuantity = parseFloat(quantityInput.value);
    let currentBasePrice = parseFloat(basePrice.getAttribute("value"));
    resOutput.textContent = currentQuantity * currentBasePrice;
  });
})()
</script>

However, there are some important warnings you should be aware of for potential issues in the future.

Avoid saving data as a number with a "," within it. Always use "." instead

If you store data in the attribute value within a paragraph tag, it may not be accessible using element.value.

If I were you, I would consider using something like

<p data-value="1.39"></p>
. Then utilize element.dataset.value to access or update it

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

The functionality of images and links is compromised when they are assigned as values to properties within a JSON object

My images and links are not working, even after declaring them globally. When I write the src directly into src, everything seems fine but the alert pops up with the same URL and img src. Can anyone help? var combo0; var combo1; var combo2; var combo3; ...

Struggling with passing the decoded user ID from Node Express() middleware to a route can be problematic

I have encountered a similar issue to one previously asked on Stack Overflow (NodeJS Express Router, pass decoded object between middleware and route?). In my scenario, I am using the VerifyOrdinaryUser function as middleware in the favorites.js route. Th ...

Transferring JSON information from Express to Backbone

I have developed a basic Backbone application and am trying to integrate JSON data from a MYSQL database using an Express server. However, when I make a GET request with Express to fetch data for Backbone, the html template in Backbone disappears, leaving ...

"Utilizing Bootstrap's Table Features within the Moodle Platform

Hey there! I'm currently in the process of updating a client's Moodle website. Our goal is to create responsive tables on the homepage, but I've encountered some challenges. Due to conflicts with other Moodle libraries, I wasn't able to ...

Several DIV elements lined up side by side

I've been working on a program that retrieves data from a database, lists some of the data when a button is clicked within the same div, and then creates new divs with buttons that have onclick events until it reaches a certain maximum value. To keep ...

Utilizing JavaScript variables to generate a custom pie chart on Google

Greetings! I must admit that I am a novice, especially when it comes to JavaScript. My background is mainly in PHP. Recently, I came across a fantastic pie chart created by Google https://developers.google.com/chart/interactive/docs/gallery/piechart I a ...

Changing the size on click using Jquery

I'm attempting to make a button shrink another element using jQuery. Here's what I have so far: $( "#img1" ).click(function() { $("#img2").css("-moz-transform:scale", "0.7, 0.7"); }); However, this solution doesn't seem to be functio ...

Transform a Javascript string variable into plain text within a pre-existing text document

Currently, I am storing user input from an HTML input as a JavaScript variable. The objective is to convert this data into plain text and save it in an existing text file. Essentially, each time the user provides input, it should be converted to plaintext ...

Can variables be declared for file paths within the HTML code in a TypeScript file?

We utilize the Vaadin designer to create the frontend of our project. Within the .ts files, we have images where we aim to establish variables for the file paths. Currently, the setup looks like this: <img src="../../themes/light/img/example.jpg&q ...

Persistent pseudo-element problem across all iterations of Internet Explorer

Encountering an issue in IE 9, 10, 11, and Edge involving pseudo elements with transparent backgrounds. The problem arises when the repeating background image appears darker in the first half compared to the second half, giving the impression of overlap be ...

Click here to view the latest Poll Results!

I have implemented AJAX to display poll results on the same page without requiring a refresh. An issue I am facing is that the poll section occupies about three times more space than the results. This causes an inconvenience for users who vote, as they ma ...

Optimizing responsiveness and side margins for high-resolution displays

Struggling with creating a website design with Bootstrap. My goal is to add margins on the sides when the screen size increases, but once I achieved it, the responsiveness of the page got disrupted. To incorporate the side margins, I enclosed the entire b ...

Location tracking functions only operational when using the local host

I managed to successfully integrate geo-location on my website while testing it on localhost. But, when I uploaded the website to an online server, I encountered a problem. I started receiving a bool(false) error message. Geo.php <?php class G ...

Incorporating the Microsoft Teams Embedded Share Button within a React-based web application

Recently, I successfully implemented the Microsoft Teams Embedded Share Button in React by following these steps: Step 1: First, I included the launcher.js script on my web app: I simply added this script to a useEffect hook: <script async defer src=& ...

What is the best way to acquire the href value from this source?

Looking to extract the dynamic value "3 Sent" from the html snippet provided. How can this be achieved? <ul class="nav nav-tabs some-tabs"> <li class="active"> <a href="#accepted" data-toggle="tab">1 Accepted</ ...

Declaring a Javascript variable within an if statement does not alter the value of the global variable

Currently, I am working on enhancing my HTML projects by using JavaScript to modify the video source. Below is the video element in question. <div> <video id="songVid" onmouseover="controlsVid()"> <source src=&qu ...

Is there a way to alter the color of a single row within a column in a jtable based on a specific condition?

statusOfPayment: { title: 'Status of Payment', width: '8%', options: {'Paid': 'Paid', 'Due': 'Due'}, create: false, ...

How about having a surprise image pop up when you click a button?

I've been working on coding a button that can change the background of my webpage to display a random image. Initially, my code seemed functional, but it was only displaying the last image listed in my series of if/else statements. I suspect that usin ...

Refresh TR when clicked

I have a HTML table that lists items from SQL, using <tr> and <td>. The table is housed within a div that is refreshed every 30 seconds with jQuery AJAX (hence the unique id on the div). Here is the HTML code: function auto_load() { $.aj ...

Why does my value always revert to 0 whenever I switch screens while utilizing async storage?

Utilizing a stack Navigator, my primary screen is tracker.js, and the secondary one is macros.js. In macros.js, I have the ability to manually input nutritional macros (calories, Fats, Carbs, Protein) and add them to my UsedDailyCalories. However, when I ...