Displaying and updating an array of values in the table's cells

I have been struggling with a simple discount calculation feature where the price should update when a user enters a value. No matter how many times I try, the array values are always printed in the first row line. The issue seems to be related to printing an array, and I would appreciate any recommendations for videos or articles that can help me understand this topic better. Thank you.

          <input type="number" id="inputValue">
          <input type="button" value="Submit" id="submitBtn">

          <table id='mytable'>
                <thead>
                        <td>Discount Products</td>
                        <td>Price One</td>
                        <td>Price Two</td>
                </thead>
                <tbody id="tbody">
                    <tr>
                        <td>Product 1</td>
                        <td class="price-one one"> 100</td>
                        <td class="price-two one">200</td>
                    </tr>
                    <tr>
                        <td>Product 2</td>
                        <td class="price-one one"> 300</td>
                        <td class="price-two one">400</td>
                    </tr>
                    <tr>
                        <td>Product 3</td>
                        <td class="price-one one"> 500</td>
                        <td class="price-two one">600</td>
                    </tr>
                    <tr>
                        <td>Product 4</td>
                        <td class="price-one one"> 700</td>
                        <td class="price-two one">800</td>
                    </tr>
                </tbody>
            </table>

I have included my script below. However, I am unable to update the price cells as intended.

const submitBtn = document.getElementById('submitBtn');
    submitBtn.addEventListener('click', function () {   

        const mytable = document.querySelector('#mytable #tbody');

        const inputValue = document.getElementById('inputValue').value;

        const prices = [];

        for (i = 0; i < mytable.rows.length; i++) {

            prices[i] = [];

            for (j = 1; j < mytable.rows[i].cells.length; j++) {
                const orginalPrice = mytable.rows[i].cells[j].innerText;

                prices[i].push(parseFloat(orginalPrice) - (inputValue/100 * orginalPrice));
            }
        }
     });

Answer №1

I'm not sure how to display them, but you can update the table content in the same way as you retrieve them like this:

mytable.rows[i].cells[j].innerText = parseFloat(orginalPrice) - (inputValue/100 * orginalPrice);

To learn more about table cells, check out this resource.

Take a look at this live example: https://jsfiddle.net/u1m0gjyk/

Answer №2

Getting closer to the solution! Rather than using this line:

prices[i].push(parseFloat(orginalPrice) - (inputValue/100 * orginalPrice));

which stores the calculated value in an array separate from the DOM, you should use the following lines:

var newPrice = parseFloat(orginalPrice) - (inputValue/100 * orginalPrice);
mytable.rows[i].cells[j].innerText = newPrice;

These lines update the innerText property of each cell with the newly calculated price (i.e. directly modifying values in the DOM):

const submitBtn = document.getElementById('submitBtn');
    submitBtn.addEventListener('click', function () {   

        const mytable = document.querySelector('#mytable #tbody');

        const inputValue = document.getElementById('inputValue').value;

        const prices = [];

        for (i = 0; i < mytable.rows.length; i++) {

            prices[i] = [];

            for (j = 1; j < mytable.rows[i].cells.length; j++) {
                const orginalPrice = mytable.rows[i].cells[j].innerText;

                var newPrice = parseFloat(orginalPrice) - (inputValue/100 * orginalPrice);
                mytable.rows[i].cells[j].innerText = newPrice;
            }
        }
     });
<input type="number" id="inputValue">
          <input type="button" value="Submit" id="submitBtn">

          <table id='mytable'>
                <thead>
                        <td>Discount Products</td>
                        <td>Price One</td>
                        <td>Price Two</td>
                </thead>
                <tbody id="tbody">
                    <tr>
                        <td>Product 1</td>
                        <td class="price-one one"> 100</td>
                        <td class="price-two one">200</td>
                    </tr>
                    <tr>
                        <td>Product 2</td>
                        <td class="price-one one"> 300</td>
                        <td class="price-two one">400</td>
                    </tr>
                    <tr>
                        <td>Product 3</td>
                        <td class="price-one one"> 500</td>
                        <td class="price-two one">600</td>
                    </tr>
                    <tr>
                        <td>Product 4</td>
                        <td class="price-one one"> 700</td>
                        <td class="price-two one">800</td>
                    </tr>
                </tbody>
            </table>

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

Customizing the CSS of the TinyMCE editor within a React application

Incorporating TinyMCE 5 into my React project has been an interesting challenge. I'm looking to personalize the editor by adjusting elements like borders and adding box shadows to the toolbar. Despite attempting to add CSS through the content_css prop ...

dividing JavaScript files in the three.js game development platform

After spending two years teaching myself unity/c#, I believe I have the coding skills to transition from an engine to a framework for better control over the environment. As I started working on first person environment features, I wanted to organize my co ...

The A-frame advances in the direction of the camera's view

I need help creating a component in A-frame that can move the player or camera based on the direction it is facing. The movement should be restricted to the x/y plane and not affect the y axis. Currently, my DOM setup looks like this: <a-entity> ...

Creating PNG and JPEG image exports in Fabric.js with the help of Node.js

Exploring the wonders of Fabric.JS specifically designed for Node.JS, not intended for web applications, I've successfully created a Static Canvas and added a rectangle to it. Now, it's time to export the image. Take a look at my code snippet bel ...

Is there a way to access an object stored on my server using JavaScript?

In implementing JavaScript, I wish to define two objects stored in a file named file.txt, and utilize them within my code. For instance, I have included the following snippet in my index.php: var counter = Number(localStorage.getItem('rans')) ...

Choose an element from within a variable that holds HTML code

I have a specific div element that I need to select and transfer to a new HTML file in order to convert it into a PDF. The issue I'm facing is related to using AJAX in my code, which includes various tabs as part of a management system. Just to prov ...

Confirm that the input into the text box consists of three-digit numbers separated by commas

Customers keep entering 5 digit zip codes instead of 3 digit area codes in the telephone area code textbox on my registration form. I need a jQuery or JavaScript function to validate that the entry is in ###,###,###,### format without any limit. Any sugge ...

Using a Button component as a TableCell in a material-ui Table

Hey there! I'm looking for some assistance in adding buttons as TableRowColumns in the material-ui Table. I'm working on implementing an approval system to approve or reject user requests, and I thought presenting them in a tabular format would b ...

What is preventing React CLI from installing the template as TypeScript?

When I run npm init react-app new-app --template typescript, it only generates a Javascript template project instead of a Typescript one. How can I create a Typescript project using the CLI? Current Node JS version: 15.9.0 NPM version: 7.0.15 ...

Using vanilla JavaScript in a node.js environment alongside Functional Reactive Programming (FRP) with bacon.js

I am interested in incorporating Functional Reactive Programming (FRP) into my project. I have come across a popular library for node.js called bacon.js that implements FRP. However, I am having trouble finding examples of how to use bacon.js in native J ...

Angular: Where does the problem lie - with the application or the deployment?

Currently, I am in the process of creating my own personal website using Angular(v4+). I understand that Angular may seem like a complex framework for a simple website, but I am using it because I am eager to improve my skills with it. During development, ...

Adjust the z-Index of the list item element

I am attempting to create an effect where, upon clicking an icon, its background (width and height) expands to 100% of the page. However, I am struggling with ensuring that the 'effect' goes underneath the this.element and above everything else. ...

Does applying a style to an element that already has the same value result in a decrease in performance? Alternatively, do all browsers simply overlook it?

Assuming I have an element with the style top: 5px, and then I execute element.style.top = "5px";, will the browser readjust its position and trigger a layout again? Or does it recognize that there is no need to change anything? (Is this behavior specified ...

alter URL parameters dynamically during API invocation

Is there a way to call an API multiple times in one request? I need the ability to dynamically adjust the date parameters for each call so that I can retrieve data for different days simultaneously. While conducting research, I came across the following c ...

How to make the last child <td> element disappear from a <table> using jQuery

Could you please help me with a jQuery code to hide the hobby field if it is empty, but still show it if there is a value present? $("tr:last-child td:last-child").css("font-weight","bold") if($("tr:last-child td:last-child").text().trim() === ""){ $(" ...

Displaying a div after a successful form submission using Jquery

I created two popup windows. One is used to ask the user whether they want to submit the form, and if they click 'yes', the form is submitted. The issue I encountered is that the other popup window should be shown after the form is successfully s ...

JavaScript - asynchronous XMLHttpRequest with increment operation

Hello, it's my debut on SO, although I've been a regular user for quite some time and found all the answers I needed here...until now. I'm currently grappling with an intricate issue involving XHR. While I consider myself a bit of a JS newb ...

Submitting form data via Ajax without refreshing the page

I am trying to submit my form using Ajax without refreshing the page. However, it seems that the $_POST values are not being picked up. I don't receive any errors, but I suspect that my form is not submitting correctly. HTML Form <form action="" ...

Comparing plain objects and class instances for modeling data objects

What is the recommended approach for creating model objects in Angular using TypeScript? Is it advisable to use type annotation with object notation (where objects are plain instances of Object)? For example, let m: MyModel = { name: 'foo' } ...

Setting up multiple RabbitMQ or other backend servers within Node configurations

As someone working in DevOps, I have encountered a situation where our developers are claiming that the Node.js software they wrote can only point to a single backend server due to Node.js limitations. This assertion seems unbelievable to me. How is it eve ...