jQuery表单验证 [英] JQuery form validation

查看:102
本文介绍了jQuery表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我的问题是,我有一个表单,我想使用jquery验证字段,如果数据正确,则让提交继续,如果没有,我通过返回false禁用默认行为(在教程,此处).
所以我用了我所说的jquery语法,当文档准备好时,我注册了按钮的click事件,问题是代码从未执行过.我用萤火虫,但没有头绪.什么都没发生,所以这是我的代码:

well my problem is that, i have a form, which i want to validate the fields using jquery, if the data is correct i let the submit continue, if no i disable the default behavior by returning false(saw that in a tutorial, here).
so i used as i said the jquery syntax, when the document is ready, i registered for the click event of the button, the problme is that code never gets executed. i used firebug but no clue. nothing happens, so here is my code:

$('#submitBtn').click(function()
{
    var password1 = $('#form_password').val();
    var password2 = $('#form_password2').val();
    if( password1 != password2)
    {
        alert("the two passwords are not equal.");
    }
    return false; //to disable the default behavior of the submit btn
});

推荐答案

检查表单提交的正确方法是检查表单的submit事件,而不是按钮的click事件.更改周围的环境以及您应该使用的内容,尽管现在它总是在执行return false;,所以永远不会发送该表格.这应该做到:

The proper way of checking a form submission is to check the form's submit event, not the button's click event. Change that around and what you have should work, although as it is right now it is always doing return false; so the form would never be sent. This should do it:

$('#myform').submit(function() {
        var motPasse1 = $('#form_motPasse').val();
        var motPasse2 = $('#form_motPasse2').val();
        if(motPasse1 != motPasse2){
            alert("Les deux mot de passe ne sont pas identiques");
            return false; // cancel form submission if passwords don't match
        }
        return true; // return true if no errors
});

最后,我希望您不要将alert留在此处用于生产目的. :)有很多比警报更好的显示用户通知的方法.查看此问题,以获取一些建议,尽管有些简单因为出现错误<div>并逐渐消失,比丑陋的默认浏览器警报框要好.

Finally, I hope you are not keeping the alert there for production purposes. :) There are much, much better ways to display user notifications than an alert. Check out this question for some suggestions, although something as simply as having an error <div> and fading it in is nicer than the ugly default browser alert box.

这篇关于jQuery表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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