class DocumentItemModal { constructor() { this.$modal = $("#document-item-modal"); this.modal = bootstrap.Modal.getInstance(this.$modal.get(0)); this.$modal.on("show.bs.modal", event => this.onShow(event)); this.$modal.on("shown.bs.modal", () => this.onShown()); this.$modal.on("hidden.bs.modal", () => this.onHidden()); this.$title = this.$modal.find(".modal-title"); this.$form = this.$modal.find("form"); this.$form.on("submit", event => this.onSubmit(event)); this.form = this.$form.get(0); this.$documentItemIdField = this.$form.find("[name=document_item_id]"); this.$descriptionField = this.$form.find("[name=description]"); this.$serialNumberField = this.$form.find("[name=serial_number]"); this.$quantityField = this.$form.find("[name=quantity]"); this.$unitPriceField = this.$form.find("[name=unit_price]"); } // Modal lifecycle onShow(event) { const $element = $(event.relatedTarget); const data = $element.data(); const { item } = data; if(item) { this.$title.text("Update Item"); this.$documentItemIdField.val(item.id); this.$descriptionField.val(item.description); this.$serialNumberField.val(item.serialNumber); this.$quantityField.val(item.quantity); this.$unitPriceField.val(item.unitPrice); } else { this.$title.text("Add Item"); } } onShown() { this.$descriptionField.trigger("focus"); } onHidden() { this.$form.get(0).reset(); this.$documentItemIdField.val(null); } onSubmit(event) { event.preventDefault(); $.post(window.location + `/submit-item`, this.$form.serialize()).then(response => { this.$modal.modal("hide"); $("#document-items-section").html(response.html); toastr.success("Item saved successfully."); DocumentPage.InitItemsSection(); }); } } $(() => new DocumentItemModal());