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