Stimulus Discourse

Relation between targets

#1

I am just starting with Stimulus.
I have a form, where you can enter an amount and then this amount should be distributed between some options if the corresponding checkbox is checked.

for example I enter 30 and check both options, each option gets 15.

I have the following code where I managed to calculate the distributed amount.
But how can I now find the input field next to the checkbox.
In other words how can I connect the distribution.active checkbox with the distribution.split input field ?

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://unpkg.com/stimulus/dist/stimulus.umd.js"></script>
    <script>
      (() => {
        const application = Stimulus.Application.start()

        application.register("distribution", class extends Stimulus.Controller {
          static get targets() {
            return [ "active", "split", "amount" ]
          }
          calcsplit() {
            var count = this.activeTargets.filter(function(el) {
              return el.checked
            }).length

            var distributedAmount = this.amountTarget.value / count
            console.log(distributedAmount)
          }
          // …
        })
      })()
    </script>
  </head>
  <body>
    <div data-controller="distribution">
      <label>
        Amount
        <input data-target="distribution.amount" type="number" data-action="distribution#calcsplit">
      </label>

      <div>
        <label>
          <input type="checkbox" data-target="distribution.active" data-action="distribution#calcsplit">
          Option 1
        </label>
        <input type="text" data-target="distribution.split">
      </div>
      <div>
        <label>
          <input type="checkbox" data-target="distribution.active" data-action="distribution#calcsplit">
          Option 2
        </label>
        <input type="text" data-target="distribution.split">
      </div>
    </div>
  </body>
</html>

s

0 Likes

#2

If they always come in pairs, you could index into one of the target arrays, and use the iterator to determine if a text field should be populated with a share of the entered amount:

for (let i = 0; this.activeTargets.length; i++) {
  if (this.activeTargets[i].checked) {
    this.splitTargets[i].value = distributedAmount;    
  }
}

I’ve made the updated example available here:

Code: https://glitch.com/edit/#!/stimulus-distributed-amount
Web: https://stimulus-distributed-amount.glitch.me

0 Likes

#3

Yes, they always come in pairs. So your solution is perfect.
Many thanks!

1 Like