Search code examples
jqueryconfirm

Confirm box with jQuery


When i normally use a confirm box for a link i do it this way:

<button type="button" class="btn btn-danger btn-sm" onclick="return confirm('Wollen Sie den Datensatz wirklich löschen?')">Delete</button>

Now i have to submit a form. In the message of the confirm box the value of an input field of the form has to be shown.

My attempt to solve this was:

<input id="endetzum" type="text" class="form-control" name="Kursende" form="formularmodal3">
<input type="submit" class="btn btn-primary" value="Auswählen" form="formularmodal3" id="buttonkursende">

$('#buttonkursende').click(function(){
var datumende = ($("#endetzum").val());
confirm('Der Kurs endet zum '+datumende);
});

It also works optically, but the form is always executed regardless of whether "ok" or "cancel" is clicked.

How can I prevent the form from being sent when "cancel" is clicked?


Solution

  • To avoid further execution with jQuery event binding, either the event function has to return false or the event.preventDefault() can be used

    $('#buttonkursende').click(function(){
        var datumende = ($("#endetzum").val());
        return confirm('Der Kurs endet zum '+datumende);
    });
    
    // or
    
    $('#buttonkursende').click(function(e){
        var datumende = ($("#endetzum").val());
        if(!confirm('Der Kurs endet zum '+datumende)) {
            e.preventDefault();
        }
    });