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.getField("document_item_id"); this.$descriptionField = this.getField("description"); this.$serialNumberField = this.getField("serial_number"); this.$quantityField = this.getField("quantity"); this.$unitPriceField = this.getField("unit_price"); this.$insuranceValueField = this.getField("insurance_value"); } getField(name) { return this.$form.find(`[name=${name}]`); } // Modal lifecycle onShow(event) { const $element = $(event.relatedTarget); const data = $element.data(); const { item, documentType } = data; this.$unitPriceField.closest("div").hide(); this.$insuranceValueField.closest("div").hide(); switch(documentType) { case DocumentTypes.DeliveryNote: this.$insuranceValueField.closest("div").show(); break; case DocumentTypes.AdvancedReplacementUnit: case DocumentTypes.Invoice: this.$unitPriceField.closest("div").show(); break; } 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); if(item.insuranceValue) { this.$insuranceValueField.val(item.insuranceValue); } } 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());