Подтвердить что ты не робот

Подтвердить предупреждение

У меня есть этот sweetalert, вызванный отправкой формы.

$(".swa-confirm").on("submit", function(e) {
        e.preventDefault();
        swal({
            title: $(this).data("swa-title"),
            text: $(this).data("swa-text"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#cc3f44",
            confirmButtonText: $(this).data("swa-btn-txt"),
            closeOnConfirm: false,
            html: false
        }, function() {

        }
        );
    });

но при нажатии подтверждения я хочу, чтобы он продолжал подавать форму...

На ум приходят плохие идеи, например:

var confirmed = false;
$(".swa-confirm").on("submit", function(e) {
    var $this = $(this);
    if (!confirmed) {
        e.preventDefault();
        swal({
            title: $(this).data("swa-title"),
            text: $(this).data("swa-text"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#cc3f44",
            confirmButtonText: $(this).data("swa-btn-txt"),
            closeOnConfirm: true,
            html: false
        }, function() {
            confirmed = true;
            $this.submit();
        });
    }
});

или перемещение swa на нажатие кнопки, а не на submit, и использование при отправке формы.

но мне не нравится это решение, оно выглядит для меня frankesteini. Конечно, есть лучший способ

4b9b3361

Ответ 1

$('#btn-submit').on('click',function(e){
    e.preventDefault();
    var form = $(this).parents('form');
    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        closeOnConfirm: false
    }, function(isConfirm){
        if (isConfirm) form.submit();
    });
});

Ответ 2

Я знаю, что это поздно, но это может помочь кому-то в будущем. Я использовал это с успехом для отправки форм с подтверждением сладости.

 $('#form_id').submit(function (e, params) {
        var localParams = params || {};

        if (!localParams.send) {
            e.preventDefault();
        }

           //additional input validations can be done hear

    swal({
                title: "Confirm Entry",
                text: "Are you sure all entries are correct",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#6A9944",
                confirmButtonText: "Confirm",
                cancelButtonText: "Cancel",
                closeOnConfirm: true
            }, function (isConfirm) {
                if (isConfirm) {
                    $(e.currentTarget).trigger(e.type, { 'send': true });
                } else {

              //additional run on cancel  functions can be done hear

            }
        });
});

Ответ 3

Я считаю, что это немного более элегантно:

$(".swa-confirm").submit(function (e) {
    e.preventDefault();
    swal({
        title: $(this).data("swa-title"),
        text: $(this).data("swa-text"),
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#cc3f44",
        confirmButtonText: $(this).data("swa-btn-txt"),
        closeOnConfirm: false,
        html: false
    }, function(){
        $(".swa-confirm").off("submit").submit();
    });
});

Ответ 4

функция testalert() {

swal(

    {
        title              : "Are you sure?",
        text               : "You want to save?",
        type               : "warning",
        allowEscapeKey     : false,
        allowOutsideClick  : false,
        showCancelButton   : true,
        confirmButtonColor : "#DD6B55",
        confirmButtonText  : "Yes",
        showLoaderOnConfirm: true,
        closeOnConfirm     : false
    }, 

    function (isConfirm) {

        if (isConfirm) {
            profileinfo.submit();
            return true;
        }

        return false;

    }

);

}

Ответ 5

Вот еще один пример: попросить пользователя подтвердить с помощью флажка.

HTML

<form id="myForm">
    <button type="submit" id="btn-submit">Submit</button>
</form>

JavaScript

$(document).on('click', '#btn-submit', function(e) {
    e.preventDefault();
    swal({
        title: 'Confirm',
        input: 'checkbox',
        inputValue: 0,
        inputPlaceholder: ' I agree with the Terms',
        confirmButtonText: 'Continue',
        inputValidator: function (result) {
            return new Promise(function (resolve, reject) {
                if (result) {
                    resolve();
                } else {
                    reject('You need to agree with the Terms');
                }
            })
        }
    }).then(function (result) {
        $('#myForm').submit();
    });
});

Ответ 6

Применить класс .swa-confirm на вход submit

$(".swa-confirm").on("click", function(e) {
    e.preventDefault();
    swal({
        title: $(this).data("swa-title"),
        text: $(this).data("swa-text"),
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#cc3f44",
        confirmButtonText: $(this).data("swa-btn-txt"),
        closeOnConfirm: true,
        html: false
    }, function( confirmed ) {
        if( confirmed )
            $(this).closest('form').submit();
    });
});

Сначала предотвратите событие кнопки. Затем запустите sweetalert, и если "подтверждено" верно, то отправьте элемент # my-form.

Извините за мой плохой английский, привет от Мексики, я использовал Google translate: v.

Ответ 7

var form = $(this).parents('form');   
    swal({
        title: "Are you sure?",
        icon: "warning",
        buttons:[
            'No, cancel it!',
            'Yes, I am sure!'
            ],
            }).then(function(isConfirm){        
                if(isConfirm){ 
                        form.submit();
                } 
});

Ответ 8

100% работает !!

Сделайте небольшой трюк, используя атрибут. В вашей форме добавьте в форму такой атрибут, как data-flag, присвойте "0" значение false.

<form class="swa-confirm" data-flag="0">
    //your inputs
</form>

В вашем jquery.

$(".swa-confirm").on("click", function(e) {
    $flag = $(this).attr('data-flag');

    if($flag==0){
        e.preventDefault(); //to prevent submitting

        swal({
            title: $(this).data("swa-title"),
            text: $(this).data("swa-text"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#cc3f44",
            confirmButtonText: $(this).data("swa-btn-txt"),
            closeOnConfirm: true,
            html: false
        }, function( confirmed ) {
            if( confirmed ){
                // if confirmed change the data-flag to 1 (as true), to submit
                $('.swa-confirm').attr('data-flag', '1');
                $('.swa-confirm').submit();
            }
        });
    }

    return true;
});