I have a table that has buttons per row that makes views/edit an item in a modal and they have a layout like so:
<td>
<button class="btn btn-sm btn-default" onclick="setModalMode('view', '8')" data-toggle="modal" data-target="#license-add" data-id="8">
<i class="far fa-eye"></i>
</button>
<button class="btn btn-sm btn-info" onclick="setModalMode('update', '8')" data-toggle="modal" data-target="#license-add" data-id="8">
<i class="far fa-edit"></i>
</button>
<button class="btn btn-sm btn-danger" onclick="setModalMode('delete', '8')" data-toggle="modal" data-target="#license-add" data-id="8">
<i class="far fa-trash-alt"></i>
</button>
</td>
It calls the setModalMode
functiton and toggles the mode of the modal:
let modal = 'div#license-add';
let $form = $('form#modal-form');
let modalMode = ''; // this is used by my AJAX function to point what URL should my requests go
let rowObjects = []; // this gets filled up by values on a different function everytime my table generates
function setModalMode(mode, id) {
loadingOverlay(false, modal);
modalMode = mode;
let title = 'Modal title';
let inputsDisabled = false;
let hasData = true;
let needsButton = true;
let isDelete = false;
if (mode === 'add') {
title = 'Add new license';
hasData = false;
} else if (mode === 'update') {
title = 'Updating license';
} else if (mode === 'view') {
title = 'Viewing license';
needsButton = false;
inputsDisabled = true;
} else if (mode === 'delete') {
title = 'Delete this license?';
inputsDisabled = true;
isDelete = true;
} else {
return;
}
if (hasData) {
let data = rowObjects['license', id];
$form.find('input#email').val(data.email);
$form.find('input#key').val(data.activation_key);
$form.find('input#expiration').val(moment(data.expiration).format('MM/DD/YYYY'));
$form.find('select#type-select').val(data.type);
$form.find('input#hidden-id').val(data.id);
} else {
$form.find(':input').val('');
}
if (needsButton) {
if (isDelete) {
$('#deleteButton', modal).show();
$('#submitButton', modal).hide();
} else {
$('#deleteButton', modal).hide();
$('#submitButton', modal).show();
}
} else {
$('#submitButton', modal).hide();
$('#deleteButton', modal).hide();
}
$('h4#modal-title', modal).text(title);
$form.find(':input').prop('disabled', inputsDisabled);
}
Although the code does its job perfectly well, I feel like my code is a mess of if
statements
id
come from? Is it, for example, in sequential ascending order in<tr>
s of the table, or is its value dynamic and not really predictable? \$\endgroup\$ – CertainPerformance Nov 19 '20 at 2:11column
option. It's predictable since it's the "primary" key of the item. \$\endgroup\$ – user208141 Nov 19 '20 at 2:14