0

我正在使用 Laravel 4 php 框架开发一个网站,并且我有一个页面显示使用 jQuery Validation 插件验证的表单。

单击表单中的按钮会通过 jQuery AJAX 请求向表单添加几个字段.load()。将字段添加到表单后,我想为这些字段添加验证规则,我使用该.rules()方法执行此操作。

但是,当我的 javascript 被调用时,我收到以下错误:

未捕获的类型错误:无法读取未定义 jquery.validate.min.js:2 的属性“表单”

作为测试,我将一个元素附加到适当的位置div并调用.rules()它,它按预期进行了验证,所以似乎由于某种原因我收到了一个错误,因为我的表单元素是使用 php 生成然后添加到页面使用.load().

这是我的代码:

有问题的页面:

<?php echo Form::open(array('id' => 'researcher-info-form')) ?>
<?php foreach($researcher_template as $slug => $title): ?>
    <tr>
        <td></td>
        <td>
            <?php echo Form::label('researcher_' . $slug, $title); ?>
            <?php echo Form::text('researcher_' . $slug); ?>
        </td>
        <td class="validation-error-message"></td>
        </tr>
<?php endforeach; ?>
...
<div id="billing-address-wrapper">
    <?php // a jQuery event loads form fields into this div dynamically. ?>
</div>
...
<?php Form::close(); ?>
...

处理这个的javascript是:

jQuery(document).ready(function($) {
    $("form").validate({
        submitHandler: submitSeqRequest,
        rules: {
        researcher_name: "required",
        researcher_email: {
            required: true,
            email: true
            },
        pi_name: "required",
        template: "required",
        primer: "required",
        dna_type: "required",
        bases_needed: "required"
        },
        errorPlacement: function(error, element) {
            error.appendTo( element.parent("td").next("td") );
        }
    });
    addLabAddress();
});

function addLabAddress() {
    $('#add-my-group').click( function() {
        $('#billing-address-wrapper').load("/order/enterLabAddress");
        $('#group_name').rules("add", {
            required: true
        })
    });
    return false;
}

位于的部分视图/order/enterLabAddress是:

<?php $billing_template = (new Lab)->billing_template; ?>
<?php foreach($billing_template as $slug => $title): ?>
    <div>
        <?php echo Form::label($slug, $title); ?>
        <?php echo Form::text($slug);   ?>
    </div>
<?php endforeach; ?>

任何人都可以帮忙吗?为什么我会收到此错误.load()?而不是.append()

4

1 回答 1

0

当您使用 .load() / AJAX 调用数据时,验证 JS 脚本不知道这些新元素是否存在。

请注意,您的验证设置是在页面最初加载时完成的

jQuery(document).ready(function($) {

您需要在每个新的 .load() 之后运行该 ready(...) 函数的内容,以便验证器远离新的 DOM 元素。

于 2013-09-10T00:57:27.573 回答