Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confirm box Twig, Symfony and Javascript

When a submit button is pushed, I want to give the user an alert to make sure they want to delete something.

So far, I have this to do so

In the Twig file

{{ form_start(form, {'attr': {'id': 'delete_form'}}) }}

And in the Javascript file

window.onload = function() {
confirmDelete();
};

function confirmDelete(){
    var el = document.getElementById('delete_form');

if (el) {
    el.addEventListener('submit', function () {
        return confirm('Are you sure you want to delete this question?');
    }, false);
}
else {
    console.log("No form found");
}}

But now, when the cancel button of the alert is clicked, the data is still being deleted.

What am I doing wrong?

like image 351
Jaimy Avatar asked Feb 03 '26 03:02

Jaimy


1 Answers

You are not preventing the form from being submited.
And in your confirm delete you will have to trigger submit event if the user clicks yes else do nothing.

// listen to the submit event
$('#delete_form').on('submit', function(e) {
    // prevent form from being submitted
    e.preventDefault();

    confirmDelete();
});

function confirmDelete() {
    var result = confirm('Are you sure you want to delete this question?');

    // I do not know what result returns but in case that yes is true
    if (result === true) {
        $('#delete_form').submit();
    }
}
like image 179
Szenis Avatar answered Feb 04 '26 15:02

Szenis