Calculate the result by multiplying each row value with the value provided as input

Check out this HTML code snippet

<form><input type="number"></form>
<table class="my-table">
<thead>
    <tr>
        <td>Header 1</td>
        <td>Header 2</td>
    </tr>
</thead>
<tbody>
    <tr data-row-num="1">
        <td>Item 1</td>
        <td>£0</td>
    </tr>
    <tr data-row-num="1">
        <td>Item 2</td>
        <td>£5</td>
    </tr>
    <tr data-row-num="1">
        <td>Item 3</td>
        <td>£10</td>
    </tr>
</tbody>

I'm trying to multiply the values in the last column of each row by the input value above and display the new values. I've been playing around with some JavaScript but could really use some help.

<script type="text/javascript>
$('input[type=number]').on("input", function () {
var tr = $('input[type=number]').closest('tr');
var num = this.value;
var numerator = tr.find('td:nth-child(2)').text();
tr.find('td:last-child').text('£' + num * numerator);

});

Your assistance would be greatly appreciated!

Answer №1

Insert your pricing within span tags for a more visually appealing display and better use of selectors. Utilize jQuery's .each() function to iterate through your prices.

<html>
    <head>
        <script src="//code.jquery.com/jquery-2.2.4.js" type="text/javascript"></script>
    </head>
    <body>
        <form id="myForm"><input type="number" id="myNumber" value="5"><input type="submit" value="Do"></form>
        <table class="my-table">
            <thead>
                <tr>
                    <td>Header 1</td>
                    <td>Header 2</td>
                </tr>
            </thead>
            <tbody>
                <tr data-row-num="1">
                    <td>Item 1</td>
                    <td>£<span class="price">10</span></td>
                </tr>
                <tr data-row-num="1">
                    <td>Item 2</td>
                    <td>£<span class="price">100</span></td>
                </tr>
                <tr data-row-num="1">
                    <td>Item 3</td>
                    <td>£<span class="price">1000</span></td>
                </tr>
            </tbody>
        </table>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#myForm ').submit(function (e) {
                    e.preventDefault();

                    // add attribute 'step="0.01"' to input, if you need to use parseFloat()
                    var input = parseInt($(this).find('#myNumber').val());
                    $('.my-table tr td > span.price').each(function (k, item) {
                        var current = parseInt($(item).text());
                        $(item).text(current * input);
                    });
                    return false;
                });
            });
        </script>
    </body>
</html>

Fiddle

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

how to create a smooth transition back to the original state after a click event

I've put in a lot of effort to make sure my code for the DECAY shapes is correct up to this point. The click event I implemented makes the shapes gradually start being affected, just as I intended. However, once I release the mouse or finger, it insta ...

Creating a spinning or swinging motion using scriptaculous shake

I want to create a unique hover effect where the item doesn't shake from side to side, but instead smoothly slides like a clock pendulum moving from 180-90 degrees. I'm not certain about the exact numbers right now. Is this achievable with Script ...

What is the method for identifying which individual element is responsible for activating an event listener?

While working on a color picker project in JavaScript for practice, I encountered an issue. I needed the #screen element to display the selected color when clicked. How can I determine which color has been clicked and pass its value to the function so that ...

The pattern on one of the cube faces is mirrored

When using an image for the cube texture, I have noticed that the image displays correctly on three out of four faces, but appears reversed on the fourth face. Below is the relevant code snippet: // Accessing the container in the DOM var container2=docume ...

Is it possible for me to use AJAX to load content from a string? I am attempting to postpone the activation of certain HTML

I need help optimizing my HTML page that includes certain sections with large Javascript files and images, which are initially hidden. Even when set to "display: none," the browser still loads all the content. One solution could be moving those sections in ...

Refinement of chosen selection

Is there a way to dynamically filter the content of a table based on the selected option? I want the table to refresh every time I change the option in the select dropdown. HTML <select ng-model="selectedGrade" ng-options="grade.Id as grade.Title f ...

AngularJs: The ability to rate or rate functionality

I've been attempting to incorporate a likes/dislikes feature into my project, but it doesn't seem to be functioning correctly. As someone new to this type of functionality, I could use some guidance. Below is the snippet of code that outlines wh ...

Unfulfilled commitment on bcrypt

I am currently facing an issue while trying to validate a user's password using bcryptjs. I have implemented a function that returns a Promise, but I am encountering an error when reaching the bycrypt.hash step - all I see is Promise { <pending> ...

Encountering errors when trying to render views in Node/Express is a common

I have set up my nodejs/express application like this; app.set('views', __dirname + './views'); app.set('view engine', 'ejs'); After that, I created a route as shown below app.get('/page/MyPage', functio ...

In Chrome, the `Jquery $('input[name=""]').change(function will not be triggered unless there is an unhandled error following it

Here is a script that I've created to make certain inputs dependent on the selection of a radio button. The 'parent' input in this case is determined by the radio button choice. Upon document load, the script initially hides parent divs of ...

Basic click event triggered every second click in JavaScript and HTML

onclick="HandleAction(\'playnow\');HandleAction(\'stop\');" This element performs two functions simultaneously. However, it only executes the actions \playnow\ and then \stop\ immediately after. ...

How to conditionally set the active class in a React component

I am new to using React and I am encountering some issues. My goal is to add an active class when any of these components are opened. I have attempted a solution but it isn't working as expected. I need assistance in adding a background color to the d ...

React: An error has occurred - Properties cannot be read from an undefined value

THIS PROBLEM HAS BEEN RESOLVED. To see the solutions, scroll down or click here I've been working on a React project where I need to fetch JSON data from my server and render it using two functions. However, I'm encountering an issue where the v ...

My Node/Express application is failing to recognize updates made to my Pug view files

I have a Node/Express app that utilizes the Pug/jade template engine, and I am able to render everything successfully. However, I am facing an issue where modifications made to my index.pug file do not reflect on the homepage, even after restarting the ser ...

Jstree's select_node function is failing to trigger

I am having an issue with the select_node.jstree function not firing properly. Below is the code snippet: $(document).ready(function () { //$("#MySplitter").splitter(); setupSplitter(); $("#divJsTreeDemo").jstree({ "themes": { "theme": "d ...

Issue: There was a problem resolving the module @react-native-community/async-storage for iOS

Attempting to run my React Native project on my iOS device has been challenging. I start the server with npx react-native start and then launch the app in Xcode, only to encounter the following error: error: Error: Unable to resolve module @react-native-co ...

Tips for managing nested objects within React state and keeping them updated

Could someone kindly point out where I might be going wrong with this code? Upon checking the console.log, it seems like the date function is functioning correctly. However, despite using this.setState, the timestamp remains unchanged. Any help would be gr ...

Switch up the side navigation panel display

Hello, I am a newcomer to bootstrap and I have successfully implemented a collapsing navbar. However, I am looking for a way to make the navbar slide out from the right side when clicked on in mobile view. Can someone provide me with some JavaScript or j ...

How can one activate a function using jQuery and then proceed to activate another function once the first function has finished executing?

My current assignment involves implementing a task using jquery. Upon loading the page, the initial jquery function will be executed. After the successful completion of the first function, it should seamlessly transition to the next function on its own. ...

Javascript - readjust weight distribution accordingly when a weight is removed

I am in possession of a dataset that shows the proportion of each test contributing to the final grade. In cases where a student has missed one or more tests, the weight is redistributed accordingly among the tests they did take. I want to determine how ...