使用 jQuery validate 验证添加到 DOM 的表单

发布于 2024-11-29 23:33:46 字数 217 浏览 1 评论 0原文

快速问题:我如何使用好的、旧的 jQuery Validate 来验证添加到页面加载后的 DOM(通过 Ajax)?

$("form#superForm").validate(options); 不起作用...

谢谢!

Quick question: How can I use good, old jQuery Validate to validate a form which gets added to the DOM (via Ajax) after the page has loaded?

$("form#superForm").validate(options); doesn't work...

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

勿挽旧人 2024-12-06 23:33:46

$("form#superForm").validate(options); 确实有效。只是您尝试在加载内容 (form#superForm) 之前附加它。

如果您希望它正常工作,则必须在加载后附加它。因此,例如:

$('#somediv').load('path/to/ajax/that/returns/form#superForm', function() {
    $("form#superForm").validate(options);
});

$("form#superForm").validate(options); does work. It's just that you're trying to attach it before the content (form#superForm) is loaded.

If you want it to work properly, you'll have to attach it after you've loaded it in. So, for example:

$('#somediv').load('path/to/ajax/that/returns/form#superForm', function() {
    $("form#superForm").validate(options);
});
烟柳画桥 2024-12-06 23:33:46

$("form#superForm").validate(选项);不起作用...

它将起作用,您只需在将表单添加到 DOM(位于 AJAX 调用的成功回调中)后调用它。我想当 DOM 中尚不存在表单时,您会在 document.ready 中调用它。

例如:

$(function() {
    // when some button is clicked we load the form:
    $('.button').click(function() {
        // we send an AJAX request to load the form
        $.post('/somescript', function(result) {
            // the AJAX request succeeds and we inject the result into the DOM:
            $('#result').html(result);

            // now we can attach the validator:
            $('#superForm').validate(options);
        });
        return false;
    });
});

$("form#superForm").validate(options); doesn't work...

It will work, you only have to call it once the form is added to the DOM which is in the success callback of your AJAX call. I suppose that you are calling it in document.ready when the form doesn't exist yet in the DOM.

For example:

$(function() {
    // when some button is clicked we load the form:
    $('.button').click(function() {
        // we send an AJAX request to load the form
        $.post('/somescript', function(result) {
            // the AJAX request succeeds and we inject the result into the DOM:
            $('#result').html(result);

            // now we can attach the validator:
            $('#superForm').validate(options);
        });
        return false;
    });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文