带有验证且无页面刷新的jQuery .submit() [英] jQuery .submit() with validation and without page refresh

查看:92
本文介绍了带有验证且无页面刷新的jQuery .submit()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个别人似乎也遇到的问题,但是我无法获得推荐的解决方案(即"return false;")来工作.任何帮助都会很棒!

I have a problem that others seem to have, but I cannot get the recommended solution (i.e., "return false;") to work. Any help would be great!

说明:

提交表单后,我要验证输入的格式正确(例如,键入电子邮件")并启动警报(例如,表单已提交".)页面刷新.当前,该警报没有出现,并且页面刷新.

When the form is submitted, I want to validate the input is in the correct format (i.e., type="email") and launch an alert (i.e., "Form submitted.") without the page refreshing. Currently, the alert does not appear and the page refreshes.

测试代码:

<!DOCTYPE html>

<html lang="en">
    <head>
        <!-- JavaScript -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>

    <body>
        <!-- Form -->
        <form>
            <input type="email" placeholder="Email" value="" size="25px" required="required" id="userEmail">
            <button type="submit" id="submit">Submit</button>
        </form>

        <!-- Alert on Submission -->
        <script>
            console.log("Ready to Go!");
            $('#submit').submit(function () {
                alert("Form submitted.");
                return false;
            });
        </script>
    </body>
</html>

推荐答案

您将要捕获表单的submit事件.按钮上没有submit事件.

You will want to catch the submit event of the form. There is no submit event on a button.

        $('form').submit(function () {
            if (*everything ok*) {
                alert("Form submitted.");
            } else {
                return false;
            }
        });

理想情况下,您可以使用ID或类(例如:

Ideally you would help identify your <form>, either with an ID or a class, i.e.:

<form id="xyz-form">

然后将选择器更改为:

$('#xyz-form').submit(...);

现在,这仅是在出现错误时停止提交表单.如果return false;不是提交回调所采用的路径,则页面将会刷新.如果您希望不刷新就将数据提交到服务器,则需要采用其他方法.

Now this is only to stop the form from submitting when there are errors. When return false; isn't the path the submit callback takes, your page is going to refresh. If you want to submit the data to the server without a refresh, you will need to approach this differently.

这篇关于带有验证且无页面刷新的jQuery .submit()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆