Showing computation result on a separate column in an HTML table

I am trying to set up a table with 3 columns. One column, total_column_price, is intended to display the calculation result of amount and device_price. How can I achieve this?

The Table

{{ Form::open(['action' => 'TransactionsINController@store', 'method' => 'POST']) }}

        <table class="table table-hover table-bordered">
            <thead align="center">
                <tr>
                    <th>Amount</th>
                    <th>Device Price</th>
                    <th><a href="#" class="btn btn-primary btn-sm addRow">
                            <i class="fa fa-plus"></i>
                        </a>
                    </th>
                    <th>Column Total Price</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <div class="form-group">
                            {{ Form::number('amount[]', 'value', ['name' => 'amount[]']) }}
                        </div>
                    </td>
                    <td>
                        <div class="form-group">
                            {{ Form::number('device_price[]', 'value', ['name' => 'device_price[]']) }}
                        </div>
                    </td>
                    <td align="center">
                        <a href="#" class="btn btn-danger btn-sm remove">
                            <i class="fa fa-times"></i>
                        </a>
                    </td>
                    <td>
                        {{ Form::text('total_column_price', '') }}
                    </td>
                </tr>
            </tbody>

            <tfoot>
                <tr>
                    <td>Total: </td>
                    <td style="border: none"><b class="total_price"></b></td>
                    <td style="border: none"></td>
                </tr>
            </tfoot>
        </table>

        {{ Form::button('<i class="far fa-save"></i> Submit', ['type' => 'submit', 'class' => 'btn btn-info'] )  }}
        {{ Form::close() }}
    

This setup involves a calculation where input in the amount and device_price columns will automatically update the value displayed in the total_column_price column.

The Script for Calculation

<script type="text/javascript">
            $('tbody').delegate('.amount,.device_price','keyup',function(){
                var tr=$(this).parent().parent();
                var amount=tr.find('.amount').val();
                var device_price=tr.find('.device_price').val();
                var total_column_price=(amount*device_price);
                tr.find(.total_column_price).val(total_column_price);
                total_price();
            });
            function total_price(){
                var total_price=0;
                $('.total_column_price').each(function(i,e){
                    var total_column_price=$(this).val()-0;
                total_price +=total_column_price;
            });
                $('.total_price').html(total_price+",00");
            }
    </script>
    

Answer №1

It looks like your code is mostly correct, but there is an issue with how you are using the JQuery find function - make sure to include quotes around the selector.

 tr.find('.total_column_price').val(total_column_price);

Consider using the .on() event handler: The .on() syntax is a newer alternative introduced in version 1.7, meant to replace .bind(), .delegate(), and .live().

There was also a minor problem in your JavaScript when accessing the parent element on keyup for an input box. It should be done as follows:

var tr = $(this).parent().parent().parent();

Give this modified code a try:

 $(function() {

  $(document).on('keyup', 'input[name="amount[]"],input[name="device_price[]"]', function() {
    var tr = $(this).parent().parent().parent();
    var amount = tr.find('input[name="amount[]"]').val();
    var device_price = tr.find('input[name="device_price[]"]').val();
    var total_column_price = (amount * device_price);
    total_price();
  });

  function total_price() {
    var total_price = 0;
    $('input[name="total_column_price[]"]').each(function(i, e) {
      var total_column_price = $(this).val() - 0;
      total_price += total_column_price;
    });
    $('.total_price').html(total_price + ",00");
  }


})

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

What is the best way to navigate through an XML document within the DOM of an HTML

I am facing an issue with HTML code. My goal is to navigate through an XML document directly from within the HTML code. Here is the XML code: <?xml version = "1.0"?> <planner> <year value = "2000"> <date month = "7" day = " ...

Assign the Firebase token to the JavaScript cookie value

Can a cookie store a token value? In my setup with js-cookie, Firebase auth/firestore, and Next.js, I am setting my cookie within the handleUser function like this: const handleUser = async (rawUser) => { if (rawUser) { const user = await fo ...

Decoding user input parameters within a vue module

It seems like I am hitting a wall when it comes to finding solutions for this particular issue. Currently, I have a component that is supposed to retrieve data from a file and display it. My intention is to only pass the filename to the component so that ...

Achieving enlightenment with Satori in NextJS: Transforming SVG to PNG in a NodeJS Environment

I am currently exploring the capabilities of satori and integrating it into my next.js api routes. (I'm unable to utilize the vercel/og package). While I have successfully set everything up, I'm facing a challenge in converting the svg image gen ...

writing a react element in an object with an svg component

I am encountering difficulties when trying to type the following. The problem lies with the TeamIcon. Here is how my object is declared. import TeamIcon from './components/icons/TeamIcon'; export const teamObject: Record< string, Recor ...

Exclude objects in array that do not match filter criteria

I am facing a challenge with filtering an array of objects. (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {tbi_tblid: 512100013, long_name: "", short_name: "", short_name2: "", trickysort: "", …} 1: {tbi_tblid: 512100013, long_n ...

A Guide to Implementing v-for in a JSON Array with Vue.js

After receiving JSON data from the server: [ {"id":"2","name":"Peter","age":"24"}, {"id":"4","name":"Lucy","age":"18"}, ] I am ...

Utilizing React portals for displaying a modal component upon clicking a table row

As I familiarize myself with React, the concept of portals in the developer documentation caught my attention. However, I am struggling to grasp how this portal component renders on-demand and how data can be passed to it to populate a modal. My current s ...

Error: stripe.redirectToCheckout does not exist and cannot be executed

Can anyone help me with implementing Stripe checkout for a website? I've been struggling because the Stripe documentation is incomplete. Here's what I have so far: import React from 'react'; import { loadStripe } from '@stripe/stri ...

Implement a feature that loads the CSS properties from a different webpage when clicked

Whenever a hyperlink is clicked, I want to create a seamless transition with three steps: 1) The content should fade out, leaving only the background image visible 2) The background image will then smoothly blend into the background image of the page lin ...

Attempting to understand why the console is not logging as anticipated when calling the function with the argument

var interval = window.setInterval(animate, 500); var i = 5; function animate() { if (i > 1) { i--; console.log(i); } else { window.clearInterval(interval); } } animate(); This block of javascript code initializes the ...

There are times when JQuery scripts fail to function correctly

Hello there. I'm having an issue with my website - www.robbiedawson.com. Sometimes, the text in the grey footer fails to load properly, including numbers and links, making navigation impossible. This happens occasionally when refreshing the page, whet ...

Troubleshooting problem with CSS aligning <dl> and <dd> tags

Utilizing <dt> and <dd> typically assumes a single line definition for dd. However, in my scenario, I have multiple entries for the definition that I need to correctly display (the exact method will be clarified after reviewing the attached ima ...

Method for retrieving list items in ajax.request jquery response

Currently, I am working on an Asp.net MVC application that includes a function with a jQuery ajax call. The response is stored in the data/result object, as expected. This response consists of multiple items within an array. I am trying to figure out how ...

Displaying information obtained from other sources

Is there a way to extract data from websites without APIs and display it on my own website using JavaScript and React? I am looking to showcase information from multiple websites on my own site, but unfortunately these websites do not have public APIs. Ho ...

Troubleshoot: Trouble with selecting the clicked item in AngularJS when using ng-repeat

Is there a way to only delete the selected item from my ng-repeat list instead of deleting all items at once? I can currently delete all items using ng-repeat, but I want to be able to delete just the clicked item. How can I achieve this? https://i.stack. ...

I'm looking to develop a custom CKEditor plug-in that will allow users to easily drag and drop elements within the editor interface

Upon observing that dragging and dropping text or images within a CKEditor editor instance does not trigger the "change" event, I devised a temporary solution by implementing code triggered by the "dragend" event. However, my ultimate goal is to create a C ...

"Efficiently calculate the total sum of columns in a datatable using dynamic JavaScript across

For further clarification, this question is an extension of a previous inquiry, which can be viewed here. In the following code snippet, I am calculating the column sum of a Shiny datatable using Javascript in order to display it directly below the table. ...

Angular controller unit testing is an essential practice in software development

I am currently working with an angular module named 'widgets'. In my app, I have used its signature as follows: var app = angular.module('widgets', [ 'widget.Panel', 'widget.List', 'services' ] ...

I am in need of granting administrator privileges to enable image uploads for an online store built with React and Next.js

Currently, I am in the process of developing an e-commerce website utilizing NextJs. One of my objectives is to grant admin privileges where an admin can upload a product image that will be showcased on the dashboard along with the rest of the product deta ...