Stimulus Discourse

Dynamic total form field from other text fields

Say I have quantity, price, discount and total field. What I want to do is dynamically update the total field on change when any of the other fields are changed.

So the total field would be = quantity * price - discount.

How do you do math like this in a stimulus controller?

This is super quick and dirty, and I didn’t test it, but basically: You want to create targets for the quantity, price and total fields, so you can access them. Then, you want to create an action that’s called when the value changes. In the controller, when you connect you want to do the calculation straight away for whatever values already exist.

HTML:

<form [...] data-controller='total'>
  <input [...] data-target='quantity' data-action='recalculate'>
  <input [...] data-target='price' data-action='recalculate'>
  <input [...] data-target='total'>
</form>

Controller:

import { Controller } from "stimulus"
export default class extends Controller {
  static targets = [ "quantity", "price", "total" ]

  connect() {
    this.recalculate()
  }

  recalculate() {
    this.totalTarget.value = this.quantityTarget.value * this.priceTarget.value
  }
}

You may need to convert strings to numbers, or do error checking in case of null, but I’ll leave that as an exercise for the reader.

Thank you! I’ll play around with this. I appreciate the pointers.

I was able to get it working based on your suggestions. Thanks!

One more item I am interested in. Say I dynamically add rows with items on them that all have totals. How would I then sum all of those totals together to get a master subtotal?

In this case I’d use child controllers. There are a few threads here on how to do that effectively, but this discussion should probably help.