I've built an express app and in the end, I added an alert for one of the delete buttons in the app. However, the alert vanishes even before I can click 'ok'.
This is my delete form
<form
action="/grades/<%=grade._id%>?_method=DELETE"
method="POST"
class="delete-form"
>
<input
type="submit"
class="btn btn-danger mt-3"
value="Delete Class"
id="delBotton"
/>
</form>
This is my main.js
file:
const delBtn = document.getElementById('delBotton');
delBtn.addEventListener('click', () =>
alertify.alert('This is an alert dialog.', function () {
alertify.message('OK');
})
);
And finally, this is my delete route:
router.delete('/:id', middleware.checkGradeOwnership, (req, res) => {
Grade.findByIdAndRemove(req.params.id, (err) => {
try {
res.redirect('/grades');
} catch (err) {
res.redirect('/grades');
console.log(err);
}
});
});
How can I get this fixed?
Since your input has type="submit"
it will by default submit the form. In order to prevent this default behavior you can either call e.preventDefault()
in the click handler, or more appropriately set the input to type="button"
since you don't plan on using this button to submit the form. Next the library alertify
seems to have a onok
event that you can use to check if the user has confirmed, which you can then use to call the form's submit function manually after the user has pressed OK, see the below runnable code snippet for a working example:
const delForm = document.getElementById('delForm');
const delBtn = document.getElementById('delBotton');
delBtn.addEventListener('click', () => {
alertify.alert('This is an alert dialog.', () => {
alertify.message('OK');
}).set({ 'invokeOnCloseOff': true, 'onok': () => delForm.submit()})
});
<!-- CSS -->
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/alertify.min.css" />
<!-- Default theme -->
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.min.css" />
<!-- JavaScript -->
<script src="//cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>
<form action="/grades/<%=grade._id%>?_method=DELETE" method="POST" class="delete-form" id="delForm">
<input type="button" class="btn btn-danger mt-3" value="Delete Class" id="delBotton" />
</form>
NOTE: initially I forgot to set invokeOnCloseOff
to true
, but it appears that this causes the onok
event to fire regardless of whether the user presses the OK button or not. The invokeOnCloseOff
should be set to true if you want to differentiate between clicking the OK button and dismissing the alert modal some other type of way. Read more here