Javascript 带有表单验证插件的 jQuery UI 对话框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4453072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:27:31  来源:igfitidea点击:

jQuery UI Dialog with Form Validation Plugin

javascriptjqueryjquery-uijquery-validatejquery-ui-dialog

提问by Justin

I am currently using the bassistance validation pluginfor my forms. And I am using a pop-up modal dialog box to house a form that needs to be validated, but for some reason it isn't calling my form... all of my ID's and references are working and I still don't any success.

我目前正在为我的表单使用bassistance 验证插件。我正在使用一个弹出式模式对话框来容纳一个需要验证的表单,但由于某种原因它没有调用我的表单......我的所有 ID 和引用都在工作,但我仍然没有任何成功。

Perhaps someone can shed some light for me. Here is my Javascript code.

也许有人可以为我提供一些启发。这是我的 Javascript 代码。

$("#addEventDialog").dialog("open");

$("#addEventDialog").dialog({
    title: 'Add Event',
    modal: true,
    buttons: {
        "Save": function() {
            $("#interestForm").validate({
                submitHandler: function(form) {
                    $("#calendarWidget2").ajaxSubmit({
                        target: "#calendarResponse",
                        dataType: 'json',
                        beforeSubmit: function () {
                            $('input[type=submit]').attr("disabled", true);
                            $("#calendarResponse").show('slow');
                        },
                        success: function(response, event) {
                            if(response.status == true) {
                                $('input[type=submit]').attr("disabled", false);
                                $("#calendarResponse").delay(5000).fadeOut('slow');

                                //If the widget says it's okay to refresh, refresh otherwise, consider it done
                                if(response.refreshEvents == '1') {
                                    $("#calendar").fullCalendar("refetchEvents");
                                }
                                // Close the dialog box when it has saved successfully
                                $("#addEventDialog").dialog("destroy");
                                // Update the page with the reponse from the server
                                $("#calendarResponse").append("Successfully Added: "+ response.title +"<br />");
                            } else {
                                $("#calendarWidget2").validate();
                                $("#calendarResponse").append("ERROR: "+ response.status +"<br />");    
                            }
                        },
                        error: function() {
                            alert("Oops... Looks like we're having some difficulties.");    
                        }
                    });
                }
            });
        },
        "Cancel": function() { 
            $(this).dialog("close"); 
        } 
    }
});

回答by MarcGuay

I solved a similar issue in 3 steps:

我分三步解决了类似的问题:

  1. Attaching the validator to the form:

    $('#your-form-id').validate();
    
  2. When the Save button of your modal form is clicked, submit the form (the validator will be triggered):

    buttons: {
      "Save": function() {
        $('#your-form-id').submit();
      },
    
  3. Move the submit logic to the validator submitHandler:

    $('#your-form-id').validate({
      submitHandler: function(form) {
        // do stuff
      }
    });
    
  1. 将验证器附加到表单:

    $('#your-form-id').validate();
    
  2. 当你的模态表单的 Save 按钮被点击时,提交表单(验证器将被触发):

    buttons: {
      "Save": function() {
        $('#your-form-id').submit();
      },
    
  3. 将提交逻辑移至验证器 submitHandler:

    $('#your-form-id').validate({
      submitHandler: function(form) {
        // do stuff
      }
    });
    

回答by mdarwi

The validators validatefunction simply sets up validation, it does not trigger it. The triggering is done automatically when the form is submitted or when a field gets written in. Try adding your validation code to the openevent:

验证器validate函数只是设置验证,它不会触发它。当提交表单或写入字段时,触发会自动完成。尝试将验证代码添加到open事件中:

$("#addEventDialog").dialog("open");
            $("#addEventDialog").dialog({
                open: function() {
                    $("#interestForm").validate({
                        ...
                    });
                }, ...

回答by Abhijit Mazumder

I know this question is old. But this one came first when I was searching for this particular problem. So I think this may help others. At last managed to achieve this.

我知道这个问题很老了。但是当我搜索这个特定问题时,这个是第一个出现的。所以我认为这可能会帮助其他人。最后设法实现了这一目标。

please see http://jsfiddle.net/536fm/6/

请参阅http://jsfiddle.net/536fm/6/

回答by George Siggouroglou

I had the same issue using jQuery Dialog plugin (http://jqueryui.com/dialog/) with jQuery Validator plugin(http://jqueryvalidation.org/). The problem is that the jQuery-UI dialog does not append to the form, it appends just before </body>, so the elements to validate are outside the <form></form> section.

我在使用 jQuery Dialog 插件(http://jqueryui.com/dialog/)和 jQuery Validator 插件(http://jqueryvalidation.org/)时遇到了同样的问题。问题是 jQuery-UI 对话框没有附加到表单,它附加在 </body> 之前,所以要验证的元素在 <form></form> 部分之外。

To solve this issue i add the "open" attribute on the Dialog initialization. Inside this attribute i add a function that wraps my Dialog div element inside a form element and then initialize the validator.

为了解决这个问题,我在对话框初始化中添加了“open”属性。在此属性中,我添加了一个函数,该函数将我的 Dialog div 元素包装在一个表单元素中,然后初始化验证器。

Also, i add the "close" attribute on the Dialog initialization. Inside this attribute i add a function that unwraps the form i wrapped on the open event and resets the validator.

此外,我在对话框初始化中添加了“关闭”属性。在这个属性中,我添加了一个函数来解开我在 open 事件上包装的表单并重置验证器。

A simple example,

一个简单的例子,

<script type="text/javascript">
var validator;
$(document).ready(function () {
    $("#dialog-id").dialog({
    autoOpen: false,
    resizable: true,
    width: 450,
    modal: true,
    // Open event => wraps the Dialog source and validate the form.
    open: function (type, data) {
        $(this).wrap("<form id=\"form-id\" action=\"./\"></form>");
        validator = $("#form-id").validate();
    },
    // Close event => unwraps the Dialog source and reset the form to be ready for the next open!
    close: function (type, data) {
        validator.resetForm();
        $(this).unwrap();
    },
    buttons: {
        "Cancel": function () {
            $(this).dialog("close");
        },
        "Create": function () {
            validator.form();
        }
    }
});
</script>

Some html for the above javascript,

上面 javascript 的一些 html,

<div id="dialog-id" title="Thematic Section">
    <div class="form_description">
        Create a thematic section for a conference type.
    </div>
    <ul style="list-style-type:none;">
        <li>
            <label class="description" for="conferencetype_id">Conference Type:</label>
            <div>
                <select id="conferencetype_id" name="conferencetype_id" style="width:150px;"> 
                    <option value="1" selected="selected">Type-1</option> 
                    <option value="2" selected="selected">Type-2</option>
                    </select>
            </div> 
        </li>
        <li>
            <label class="description" for="title">Title:</label>
            <div>
                <input id="title" name="title" type="text" maxlength="100" value="" style="width:350px;" required/> 
            </div> 
        </li>
    </ul>
</div>

回答by timbrown

Try something like this. Put your form validate stuff outside dialog script or i guess the open callback would work as well.

尝试这样的事情。将您的表单验证内容放在对话框脚本之外,或者我想打开的回调也可以工作。

 buttons : {
       "Cancel" : function() {
            $(this).dialog('close');
        },
        "Submit" : function() {
            var isValid = $("#yourForm").valid();
            if(isValid) {
                var formData = $("#yourForm")serialize();
                // pass formData to an ajax call to submit form.

            }
           return false;
        }
 },