import { Controller } from "@hotwired/stimulus" export default class extends Controller { static targets = ["select", "button"] unitChanged() { if (this.selectTarget.value && this.selectTarget.value !== this.selectTarget.dataset.defaultUnitId) { Turbo.StreamElement.prototype.enableElement(this.buttonTarget) } else { Turbo.StreamElement.prototype.disableElement(this.buttonTarget) } } setDefault() { const select = this.selectTarget const form = document.createElement('form') form.action = this.buttonTarget.dataset.path form.method = 'post' form.dataset.turboStream = 'true' const methodInput = document.createElement('input') methodInput.type = 'hidden'; methodInput.name = '_method'; methodInput.value = 'patch' const unitInput = document.createElement('input') unitInput.type = 'hidden'; unitInput.name = 'quantity[default_unit_id]'; unitInput.value = select.value form.appendChild(methodInput) form.appendChild(unitInput) form.addEventListener('turbo:submit-end', event => { if (event.detail.success) { select.dataset.defaultUnitId = select.value this.unitChanged() } form.remove() }) document.body.appendChild(form) form.requestSubmit() } }