用javascript调用表单验证事件时,为何return false了仍是把表单submit了?

表单提交前,都会有定义一个验证的方法以对用户提交的内容进行限定,今天写到了这个,但出现了一个好郁闷的东西,就是一点提交了,调用我本身写的一个CheckForm()方法时,我明明写了return false了,但它仍是提交到服务器了,好不郁闷!而后仔细检查才发现,原来是漏了个return,下面先看出错的代码:javascript

 1 <script src="../js/jquery-1.6.js" type="text/javascript"></script>
 2 <script type="text/javascript">
 3     $(function () {
 4         $("#btnAdd").click(function () { CheckForm() });
 5         $("#btnSave").click(function () { CheckForm() });
 6     });
 7 
 8             
 9     function CheckForm() {
10                 
11         if ($("#ddlClassesType_2").val() == "--請選擇--") {
12             alert("請選擇表單的類型");
13             $("#ddlClassesType_2").focus();
14             return false;
15         }
16 
17         if ($("#txtWebName").val() == "") {
18             alert("請輸入網址的名稱");
19             $("#txtWebName").focus();
20             return false;
21         }
22 
23         if ($("#txtWebNameAlias").val() == "") {
24             alert("請輸入網址的別稱");
25             $("#txtWebNameAlias").focus();
26             return false;
27         }
28 
29         if ($("#ddlVisitorType").val() == "-1") {
30             alert("請選擇網址的訪問類型");
31             $("#ddlVisitorType").focus();
32             return false;
33         }
34 
35         if ($("#txtSortNo").val() == "") {
36             alert("請輸入序號");
37             $("#txtSortNo").focus();
38             return false;
39         }
40 
41         if ($("#txtWebUrl").val() == "") {
42             alert("請輸入網址");
43             $("#txtWebUrl").focus();
44             return false;
45         }
46 
47         if ($("#txtWebDesc").val() == "") {
48             alert("網址備注信息也不能為空,請輸入。");
49             $("#txtWebDesc").focus();
50             return false;
51         }
52         return true;
53     }
54 </script>

 

我回想了一下之前写过的javascript经验,也碰到过相似的问题,当时是用javascript直接用的,相似于下面这样子:java

<asp:Button ID="btnSave" runat="server" Text="保存" Width="50px" OnClick="btnSave_Click" OnClientClick="return CheckForm();" />

 

看到CheckForm()前面的return 没有?其实jquery也是同理的,就是少了这个家伙,因此,只要把第4跟第5行改为下面这样子就OK了jquery

$("#btnAdd").click(function () { return CheckForm() });
$("#btnSave").click(function () { return CheckForm() });

 

 

虽然简单,但不会的时候真的要想半天,此次把它记下来,之后也能回顾一下,但愿能帮到有一样困惑的朋友。服务器

相关文章
相关标签/搜索