使用JSP页面中的jquery使用一个提交按钮验证两个表单

时间:2016-06-07 05:19:50

标签: javascript jquery html

这是我的代码

$(document).ready(function(){
    $("form#one").validate({  // initialize form validation on form 1
        // rules & other options
        messages: {
            input1: "salam"
        },
        errorPlacement: function(error, element) {
            element.focus(function () {
                $("#msg_required").html(error);
            }).blur(function () {
                $("#msg_required").html('');
            });
        }
    });
    $("form#two").validate({ // initialize form validation on form 2
        // rules & other options,
        messages: {
            input2: "bah"
        },
        errorPlacement: function(error, element) {
            element.focus(function () {
                $("#msg_required").html(error);
            }).blur(function () {
                $("#msg_required").html('');
            }); // default error placement
        },
        submitHandler: function(form) {
            if ($("form#one").valid()) {  // test to see if form 1 is valid
                $( "form#two" ).submit();
            }
            return false;
        }
    });
});
<!-- FORM #1: -->
<br/>
<form action="#" id="one">
    <input type="text" name="input1" class="required" />
</form>

<!-- FORM #2: -->
<br/>
<form action="#" id="two">
    <input type="text" name="input2" class="required" />
    <br />
    <span dir="rtl" id="msg_required" class="msg_required"></span>
    <br /><br />
    <input type="submit" />
</form>

当我提交表单2时,表单1中的错误消息未显示。
includes jQuery_Validation_Plugin_1.9.0.js and jquery-1.9.1.js

1 个答案:

答案 0 :(得分:1)

表单1错误无法显示,因为单击提交按钮时未提交。您应该运行以下代码:

//first the submit button should not be in between any `form` tag
<!-- FORM #1: -->
<br/>
<form action="#" id="one">
    <input type="text" name="input1" class="required" />
</form>

<!-- FORM #2: -->
<br/>
<form action="#" id="two">
    <input type="text" name="input2" class="required" />
    <br />
    <span dir="rtl" id="msg_required" class="msg_required"></span>
    <br /><br />
</form>

<!--place the submit button here-->
<button id="submit_btn">submit</button>

现在创建一个函数,在单击按钮

时提交2个表单
$("#submit_btn").on('click' function (){
    //run your from submission here
})