lundi 21 novembre 2016

Prevent Form-Redirect (with Checkboxes)

I'm using this fancy Javascript to prevent the redirect on form submit:

$(function() {

    // Kontakt-Formular in das Script laden
    var form = $('#contact-form-edc');

    $(form).submit(function(e) {
        // Den Weiterleitung stoppen
        e.preventDefault();

        // Die Kontakt-Formular Daten in das Script laden
        var formData = $(form).serialize();

        // Das Kontakt-Formular absenden
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })

        .done(function(response) {
            // Erfolgreiche Meldung
         document.getElementById('success').style.display = "";
          document.getElementById('error').style.display = "none";

            // Das Kontakt-Formular leeren
            $('input').val('');
   $('textarea').val('');
   $('.button').val('Abschicken');
   $('input[name=datenschutz]').attr('checked', false);
        })
        .fail(function(data) {
            // Fehler Meldung
           document.getElementById('error').style.display = "";
            document.getElementById('success').style.display ="none";
        });

    });

});

Im using it in combination with a form-validation (it is checking every "required" input-field). It works quite fine but do not mind the checkboxes in my form which have the attribute "required" as well.

If the user is filling out the form (but leaves the checkbox field (required) empty), the form is still submitting. If I get rid of the javascript, the validation works fine but the form will redirect the user.

You can check it out, if you want.




Aucun commentaire:

Enregistrer un commentaire