How to “stop” closing modal if form invalid

浪尽此生 提交于 2019-12-25 06:02:42

问题


I have a form in a Semantic UI Modal, and I use the jQuery Form Plugin (http://malsup.com/jquery/form/#validation) to submit the form via ajax. The "submit" process of the form is triggered by the modal "ok" button. But if the form is invalid, the modal is still closed.

How can I "stop" the modal close procecedure?

Thanks a lot!

edit

Code snippets:

the modal:

    <div class="ui modal" id="add-item-modal">
    <i class="close icon"></i>
    <div class="header">
        Eintrag hinzufügen
    </div>
    <div class="content">
        {{ include('adachauerJobsBundle:CV/forms:training.html.twig') }}
    </div>
    <div class="actions">
        <div class="ui buttons">
            <div class="ui button" onclick="$('#modal-form').reset();">Abbrechen</div>
            <div class="ui button primary" onclick="$('#modal-form').submit();">Speichern</div>
        </div>
    </div>
</div>

Modal show:

    $('.show-modal').click(function(e) {
         e.preventDefault();
         $($(this).attr('data-modal-id')).modal('show');
    });

Form submit:

    var cvDataTarget = '#cv-data-target';
$('.ajax-form').submit(function() {
    $(this).ajaxSubmit({
        beforeSubmit: function(formData, jqForm, options) {
            for (var i=0; i < formData.length; i++) {
                if (!formData[i].value) {
                    console.log(0);
                    alert('Bitte fülle alle erforderlichen Felder aus, um den Eintrag zu speichern.');
                    $('#'+formData[i].name).focus();
                    return false;
                }
            }
        },
        success: function(t) {
            console.log(t);
            if (t.success == true) {
                $(cvDataTarget).html($(cvDataTarget).html()+ t.html);
            } else {
                alert(t.error);
            }
        }
    });

    return false;
});

回答1:


You can simply add a return false; in the modal's callback to prevent it from closing:

$('.show-modal').click(function(e) {
    e.preventDefault();
    $($(this).attr('data-modal-id')).modal('show',{
        onApprove : function() {
            return false; //block the modal here
        }
    });
});

And once you're done, you can call

$(theModal).modal('hide');



回答2:


Call preventDefault() just before submitting the form:

 $('#theSubmitButton').click(function (e) {
      e.preventDefault();
      $('#modal-form').submit();
 });

Modify the submit button by removing onclick() and giving "him" a name:

 <div class="ui button primary" id="theSubmitButton">Speichern</div>


来源:https://stackoverflow.com/questions/30894806/how-to-stop-closing-modal-if-form-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!