为啥 validateform() 的返回为 false 时提交表单?

Posted

技术标签:

【中文标题】为啥 validateform() 的返回为 false 时提交表单?【英文标题】:why form is submitted while the return from validateform() is false?为什么 validateform() 的返回为 false 时提交表单? 【发布时间】:2015-08-19 00:15:46 【问题描述】:

我有我在 jquery mobile 中进行 javascript 验证的代码。但问题是表单已提交,即使验证表单返回 false。请回复可能是什么原因?下面是我的代码。

<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.css" rel="stylesheet" />
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>  
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>  
    <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
    <script>
    // Validate Contact Table
    function validateContact() 
        var emergencyContactElt = document.getElementById("Emergency_Contact");
        var emergencyContactEltRows = emergencyContactElt.rows;
        var maxrowNbr = emergencyContactElt.rows.length;
        var error = 0;
        for (var i = 1; i < maxrowNbr; i++) 
            // Validation for First Name
            if (emergencyContactEltRows[i].cells[1].children[0].children[0].value == "") 
                emergencyContactEltRows[i].cells[1].children[0].children[0].style.background = '#e35152';
                emergencyContactEltRows[i].cells[1].children[0].focus();
                error = error + 1;
             else 
                emergencyContactEltRows[i].cells[1].children[0].children[0].style.background = 'white';
            

            // Validation for Last Name
            if (emergencyContactEltRows[i].cells[2].children[0].children[0].value == "") 
                emergencyContactEltRows[i].cells[2].children[0].children[0].style.background = '#e35152';
                emergencyContactEltRows[i].cells[2].children[0].focus();
                error = error + 1;
             else 
                emergencyContactEltRows[i].cells[2].children[0].children[0].style.background = 'white';
            

            // Validation phone number
            if (emergencyContactEltRows[i].cells[3].children[0].children[0].value == "") 
                emergencyContactEltRows[i].cells[3].children[0].children[0].style.background = '#e35152';
                emergencyContactEltRows[i].cells[3].children[0].focus();
                error = error + 1;
             else 
                emergencyContactEltRows[i].cells[3].children[0].children[0].style.background = 'white';
            

        

        if (error > 0) 
            return false;
         else 
            return true;
        
    

    //Validate Form 
    function validateForm() 
        var error = 0;
        if (!validateContact()) 
            error++;
            alert("Contact");
        

        // Don't submit form if there are errors
        if (error > 0) 
            alert(error);
            alert("highlight fields are required");
            return false;
         else 
            return true;
        
            </script>
</head>

	<body>
		<form name="submitform" id="submitform" method="post" action="%bind(:25)" onsubmit="return validateForm();" >
		<table id="Emergency_Contact" name="Emergency_Contact">
			<tbody>
				<tr>
    				<th>Relationship</th>
    				<th>First Name</th>
					<th>Last Name</th>
					<th>Phone</th>
					<th>Email Id</th>
					<th>Consent</th>
					<th>Working/Studying In ADU</th>
					<th>Employee Id/Student ID</th>
					<th>Add/Delete</th>
 				</tr>
				<tr>
					<td>
						<select name="Relationship" id="Relationship" class="Relationship" style="width:100%"> 
							<option value="B" selected="">Brother</option>
							<option value="D">Daughter</option>
							<option value="E">Employee</option>
							<option value="ER">Employer</option>
							<option value="ES">Ex-Spouse</option>
						</select>
					</td> 
					<td> 
						<input name="First_Name" id="First_Name" value="" style="width:100%" type="text">
					</td> 
						<input name="Last_Name" id="Last_Name" value="" style="width:100%" type="text">
					</td> 
					<td>
						<input name="Phone" value="" style="width:100%" type="text">
					</td>   
				</tr> 
			</tbody>
		</table>
			<div data-role="ui-grid-a">
             	<div class="ui-block-a" style="width:50%">
					<input type="button" id="Previous" value="Previous" onclick="window.location.href='%bind(:24)'"/>
 				</div>
				<div class="ui-block-b" style="width:50%">
					<!--<input type="Submit" id="Submit" value="Save and Next" class="ui-btn ui-shadow"/>-->
					<input type="Submit" id="Submit" value="Save and Next" />
				</div>
			<div>
		</form>
	</body>
</html>

【问题讨论】:

你在用IE吗?哪一个? 控制台错误:Uncaught TypeError: Cannot read property 'children' of undefined on if (document.getElementById("Emergency_Contact").rows[i].cells[3].children[0].children[0].value == "") 为什么不使用jQuery,因为你已经包含了它? jquery 表单验证将适合这里! :) 您在validateForm() 内声明var error,因此它仅在该范围内可用。但是你在外面测试它,所以你永远不会得到if(error &gt; 0) 【参考方案1】:

您有控制台错误。但是当你拥有 jQuery 时为什么不使用它 - 这里你不再需要 onsubmit,只需添加

.error  background-color:#e35152

并且拥有

$(function() 
  $("#submitform").on("submit", function(e) 
    $(this).find("input[type='text']").each(function() 
      $(this).toggleClass("error", $.trim(this.value) == "");
    );
    if ($(".error").length > 0) 
      e.preventDefault();
      alert("highlight fields are required");
    
  );
);

$(function() 
  $("#submitform").on("submit", function(e) 
    $(this).find("input[type='text']").each(function() 
      $(this).toggleClass("error", $.trim(this.value) == "");
    );
    if ($(".error").length > 0) 
      e.preventDefault();
      alert("highlight fields are required");
    
  );
);
 .error 
   background-color: #e35152
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="submitform" id="submitform" method="post" action="%bind(:25)">
  <table id="Emergency_Contact" name="Emergency_Contact">
    <tbody>
      <tr>
        <th>Relationship</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Phone</th>
        <th>Email Id</th>
        <th>Consent</th>
        <th>Working/Studying In ADU</th>
        <th>Employee Id/Student ID</th>
        <th>Add/Delete</th>
      </tr>
      <tr>
        <td>
          <select name="Relationship" id="Relationship" class="Relationship" style="width:100%">
            <option value="B" selected="">Brother</option>
            <option value="D">Daughter</option>
            <option value="E">Employee</option>
            <option value="ER">Employer</option>
            <option value="ES">Ex-Spouse</option>
          </select>
        </td>
        <td>
          <input name="First_Name" id="First_Name" value="" style="width:100%" type="text">
        </td>
        <td>
          <input name="Last_Name" id="Last_Name" value="" style="width:100%" type="text">
        </td>
        <td>
          <input name="Phone" value="" style="width:100%" type="text">
        </td>
      </tr>
    </tbody>
  </table>
  <div data-role="ui-grid-a">
    <div class="ui-block-a" style="width:50%">
      <input type="button" id="Previous" value="Previous" onclick="window.location.href='%bind(:24)'" />
    </div>
    <div class="ui-block-b" style="width:50%">
      <!--<input type="Submit" id="Submit" value="Save and Next" class="ui-btn ui-shadow"/>-->
      <input type="Submit" id="Submit" value="Save and Next" />
    </div>
    <div>
</form>

【讨论】:

【参考方案2】:

最初的问题是因为在“last_name”输入之前缺少

。这导致“validateContact”函数抛出异常。

对于像这样的所有简单需求,最好使用原生的东西而不是 jquery。尝试使用 'querySelector' 方法来选择要处理的 DOM 节点。

【讨论】:

以上是关于为啥 validateform() 的返回为 false 时提交表单?的主要内容,如果未能解决你的问题,请参考以下文章

为啥 fa-rotate-90 图标在 Chrome 中显得模糊?

正则表达式[\u4E00-\u9fa5]为啥能匹配到数字,字母和某些符号?

为啥需要重定位同一文件中的全局符号?

为啥我只能在类型参数位置传递部分应用的类型构造函数?

为啥 applicationState 被返回为零?

为啥 ApplicationsDocumentsDirectory 为单元测试返回 null?