Sum up the total value for every item in the VueJS list

My goal is to create a jobcard for a vehicle with works. I want to display the total amount by adding up the painting charge and denting charge inputs to the estimated amount input for each indexed item. This means that when I click the Add item button, it should populate with four input values: Description, Painting Charge, Denting Charge, EST Amount.

Vuejs Code

<template>
    <div>
        <form v-on:submit.prevent="save">
            <h3 class="text-center py-2 font-weight-bold"><template v-if="edit_id">Edit</template><template v-else>Add</template> Jobcard</h3>
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Chasis No:</label>
                        <input type="text" v-model="jobcard.chasis_no" class="form-control" required placeholder="Chasis No">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Model:</label>
                        <select class="form-control" v-model="jobcard.model" required>
                            <option value="">Select a Model</option>
                            <option v-for="model in models" :value="model.name">{{ model.name }}</option>
                        </select>

                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Color:</label>
                        <select class="form-control" v-model="jobcard.color" required>
                            <option value="">Color</option>
                            <option v-for="color in colors" :value="color.name">{{ color.name }}</option>
                        </select>

                    </div>
                </div>
            </div>
            <!-- Rest of the form structure goes here -->
        </form>
    </div>
</template>

<script>


export default {
   
    props:['edit_id','models','variants','colors','supervisors','technicians','types'],
    created(){
        if(this.edit_id)
        {
            this.edit()
        }
        else
            this.add_item();
    },
    data () {
        return {
            // Data properties go here
        }
    },
    methods : {
        // Methods go here
    },
    computed: {
      // Computed properties go here
    },
}
</script>

<style lang="css" scoped>

</style>

Answer №1

To enhance your code, consider creating a new function that accepts the item parameter and calculates the total amount by adding the Painting Charge (painting_charge) and Denting Charge (denting_charge).

methods : {
    // ...
    calculateEstimatedAmount(item) {
        return parseFloat(item.painting_charge || 0) + parseFloat(item.denting_charge || 0);
    },
    // ...
}

After defining the method, update your template by using the newly created function as follows:

:value="calculateEstimatedAmount(item)"
. This will bind the Estimated Amount field to the result of the calculateEstimatedAmount method. To ensure the correctness of the value, consider setting the input field as read-only.

<tbody>
    <tr v-for="(item,key) in items">
        <!-- tds -->
        <td>
            <input type="text" pattern="[0-9.]{1,}" :value="calculateEstimatedAmount(item)" class="form-control" readonly placeholder="Estimated Amount" >
        </td>
        <!-- tds -->
    </tr>
</tbody>

This approach ensures that the Estimated Amount for each listed item will be automatically updated whenever changes occur in the Paint or Dent Charge values.

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

Is it possible to use the LINK method/verb with AngularJS $http?

Can the $http method in AngularJS be used to send ajax requests using the LINK/UNLINK method? I have checked the AngularJS documentation and only found a list of available methods: $http.get $http.head $http.post $http.put $http.delete $http.jsonp $http. ...

Utilizing JQuery to detect a combination of ctrlKey and mouse click event

Looking for assistance with JQuery as I am new to it and still learning the logic. My goal is to determine which index of a textarea was clicked while holding down the CtrlKey. How can I combine an onclick event with a keyboard event and assign a function? ...

Tips for switching images in a grid using jQuery

I have implemented an image grid using flexbox on a website I am developing. The grid consists of 8 boxes, and my goal is to randomly select one box every 2 seconds and assign it one of 12 random images. My strategy involves creating an array containing UR ...

The Vue.js transition class is fading away prematurely, before the animation is complete

I recently created a Vue component that utilizes a JavaScript hook for transitioning purposes, specifically to call velocity.js and animate my components. Check out my component in action here While the slideDown functionality of the component is working ...

Issue with page not updating after local storage change and returning to previous page

I have encountered an issue where in Firefox and Safari, the value retrieved from localstorage on the first page is not updated until I manually refresh the page after setting the localstorage value on the second page. Disabling the cache did not resolve t ...

The switch/case function I implemented is functioning correctly, however, an error is being displayed in the console stating "Cannot read property 'name' of null"

Check out the live codepen demo here After selecting "elephant" from the third dropdown, the console.log(brand.name) displays "elephant" as expected and executes the rest of the switch statement successfully. However, there seems to be a console error oc ...

Effective technique for connecting client-side JavaScript with server-side node.js

I am striving to create a compact website featuring field auto-completion, drawing suggestions from the server's database (utilizing Node.js + MySQL). What approaches can I take to establish client-server communication as the user inputs data into a ...

Initiate an AJAX request within an existing AJAX request

On one of my pages, page A, I have a form that passes parameters to a script using AJAX. The results are loaded into div B on the same page. This setup is functioning properly. Now, I want to add another form in div B that will pass parameters to a differe ...

The Oscillator node in the Web Audio API is unable to be started more than once due to an error

Every time I attempt to start, stop, and then start my oscillator again, I encounter the following error message: Uncaught InvalidStateError: Failed to execute 'start' on 'OscillatorNode': cannot call start more than once. Although usi ...

Looking to display database information using javascript

Currently, I am working on a project involving PHP code where I retrieve variables from an input and utilize AJAX. Here is the code snippet: $.ajax({ type: "GET", url: "controller/appointment/src_agenda.php", data: { function: "professional", ...

Discover the magic of Bootstrap 3.0 Popovers and Tooltips

I'm struggling with implementing the popover and tooltip features in Bootstrap. While I have successfully implemented drop downs and modals, the tooltips are not styled or positioned correctly as shown in the Bootstrap examples, and the popover featur ...

Leveraging JavaScript to unpack references within a intricate object network obtained through SignalR/Json.NET

Utilizing SignalR to send back a complex object hierarchy to my JavaScript client has proven challenging. The JSON structure produced by SignalR/Json.NET contains multiple references to the same object, resulting in a convoluted output like this: { &qu ...

Add a message displaying the error in the input field using jQuery Validation

Is there a way to append the jQuery Validation error messages to the input field or get help with positioning them properly? The random popping up of error messages is causing chaos in the form layout. I prefer to have the error messages displayed undern ...

What is the method of using "*" as the value for allowedModules in a jsreport configuration file to enable all modules?

I am having an issue when trying to generate a report using jsreport STUDIO. The error message I received is as follows: An error occurred - Error during rendering report: Unsupported module in scripts: request. To enable require on a particular module, ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Tips for displaying an edit action icon when hovering over specific text

Looking for a way to display or hide the edit icon when hovering over specific text? Take a look at this snippet of HTML code: <ul> <li> <a id="pop" href="javascript:;;" data-content="test Desc" data-id="123"> &l ...

What is the best way to change an int32 to a float32 in Deeplearn.js?

In December 2017, this code did the job perfectly. However, after updating Deeplearn.js to the latest version, it no longer functions as expected: math.scope(function(keep, track) { var i = track(dl.Array3D.fromPixels(rawImageData, 4)); i = math.multi ...

Using v-model in Vue with jQuery integration

I wrote a jQuery code that is executed when the mounted hook runs mounted() { this.$progress.finish(); var geocoder = new google.maps.Geocoder(); var marker = null; var map = null; function initialize() { var $latitude = document.getEl ...

Which NPM packages are necessary for implementing modular Vue components?

While I have experience with traditional multi-page applications created using HTML + JS libraries and server-side rendering (SSR), I am relatively new to modern web development. Currently, I am learning Vue JS (the latest version) through online tutorials ...

Which is more effective: Layering multiple canvases in the DOM or consolidating all drawing on a single canvas?

In my previous projects, I have had experience working with layered canvases. While some of my colleagues swear by this approach, I find myself skeptical about its effectiveness. My primary concerns are: If multiple canvases are layered and one undergoes ...