为什么当我点击它时,我的表单提交按钮不会进入下一页? [英] Why isn't my form submit button not going to a next page when I click on it?

查看:171
本文介绍了为什么当我点击它时,我的表单提交按钮不会进入下一页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄明白为什么表单的提交此表单按钮不会将我带到我在< form ... action =submit form.html中指定的另一个HTML页面 method =get> 属性,不仅如此,而且当我输入错误的名字,电子邮件地址和订单号以及订单日期时,它不会返回我在我的if-else codes using JavaScript。



以下是我在表单中使用的JavaScript代码。



  var $ = function(id){return document.getElementById(id); } var submitForm = function(){var FirstName = $(firstName).value; var OrderNumber = $(orderNumber).value; var DateOfOrder = $(date_of_order).value; var emailAddress = $(email_address).value; var isValid = true; if(FirstName!==Cherry,Micheal,Sandra,Cookie){$(firstname_error)。firstChild.nodeValue =这个人不存在。的isValid = FALSE; if(OrderNumber!== 3134,4234,9234,3566){$(orderNumber_error)。firstChild.nodeValue =无效的订单号。其他{$(firstname_error)。firstChild.nodeValue =;} ;的isValid = FALSE; } else {$(orderNumber_error)。firstChild.nodeValue =;} if(DateOfOrder!=='12-07-23','15-04-24','16 -02-01','14 -01-12'){$(date_of_order_error)。firstChild.nodeValue =日期在系统中不存在;的isValid = FALSE; } else {$(date_of_order_error)。firstChild.nodeValue =;} if(emailAddress!=cherryjackson@gmail.com,michealroberts@yahoo.com,sandrabell@hotmail.com,cookiedanny @ outlook.com){$(email_address_error)。firstChild.nodeValue =电子邮件不存在;的isValid = FALSE; } else {$(email_address_error)。firstChild.nodeValue =;} if(isValid){//如果所有条目都有效,则提交表单$(cookie_form)。 }} window.onload = function(){$(form_submission)。onclick = submitForm; $( EMAIL_ADDRESS)专注()。 }    body {background-color:#FBFBE8;} / *告诉HTML5找到我的操作系统所具有的字体类型,然后将其用于标题1,同时也将第一个标题置于中间* / h1 {font-family:Arial,Helvetica,sans-serif;文本对齐:中心; } / *如果HTML源文件中的第一段不可用,则告诉HTML5使用任何字体类型。还从段落的左边缘清除了一些空白区域,最后告诉它给该段落20个像素的大小。 * / p {font-family:Arial,Helvetica,sans-serif; padding:20px;字体大小:20像素; } label {float:left;宽度:11em; text-align:right; font-family:Arial,Helvetica,sans-serif;颜色:#800000;} input {margin-left:1em;边距:.5em; } span {color:red; } .field_set_1 {border-color:purple; border-style:solid;}#form_submission {background-color:black; color:white;} legend {font-family:Arial,Helvetica,sans-serif;颜色:蓝色; } / *所有的类只是用于定位和浮动四个相同的图像周围的表单输入信息* /。Wrap1 {float:right;保证金:40像素;宽度:200像素; height:200px;}。Wrap2 {float:left;保证金:40像素;宽度:200像素; clearfix {clear:both;}  

<!DOCTYPE html>< html>< head>< title> Cookie订单表单< / title>< link rel =stylesheethref =First_Design.css>< script src = cookieform.js< / head>< body>< h1> Cookie订单表单< / h1>< p>此表单是一个cookie订单,用于从达朗饼干公司并且必须填写以下内容,以便每个客户收到最终消息,告诉他们何时他们的订单已准备就绪。< / p>< IMG class =Wrap1SRC =cookie.gifalt = cookie>< IMG class =Wrap2SRC =cookie.gifalt =cookie2><! - 客户点击后将被发送到名为submit form.html的HTML页面提交此表单按钮。下面的代码是这样做的。 - > < DIV> < form id =cookie_formname =cookie_formaction =submit form.htmlmethod =get>< fieldset class =field_set_1> <! - 下方设定表格的标题 - > <图例>客户订单表单信息:< / legend> <! - 创建第一个左标签以指定应在文本框中放置标签右侧的内容。下面的其他部分也是如此。 - > < label for =firstName>名字:< / label> < input type =textid =firstNamename =firstName> < span id =firstname_error> *< / span>< br> < label for =orderNumber>订单号码:< / label> < input type =textid =orderNumbername =orderNumber> < span id =orderNumber_error> *< / span>< br> < label for =date_of_order>订单日期:< / label> < input type =textid =date_of_ordername =date_of_order> < span id =date_of_order_error> *< / span>< br> < label for =email_address>电子邮件地址:< / label> < input type =textid =email_addressname =email_address> < span id =email_address_error> *< / span>< br> <标签>&安培; NBSP;< /标签> < input type =buttonid =form_submissionvalue =提交此表单> < /字段集> < / div>< div class =clearfix>< / div>< IMG class =Wrap1SRC =cookie.gifalt =cookie>< IMG class =Wrap2SRC =cookie.gifalt =cookie2>< / body>< / html>

解决方案

你的代码有很多错误,但最大的是你的验证测试,结构:

  if(FirstName!==Cherry,Micheal,Sandra,Cookie)

您无法使用逗号测试 firstName - 分离值列表。每个人都必须单独进行测试,并且必须在他们之间使用复合逻辑运算符:

  if(FirstName!==Cherry &&& FirstName!==Micheal&& 
FirstName!==Sandra&&&&FirstName!==Cookie)

您还使用标准按钮而不是提交按钮,这可能会导致在某些情况下,当ENTER键被击中时,所有验证都会被忽略。始终使用提交按钮并在提交事件中进行验证。



请参阅我的重构和重新组织的代码解决方案用于内联评论。
$ b


Stack Overflow片段环境(下)不适用于forms
(因为它是沙盒版),但可以运行相同的代码 此处


事件模型,而不是节点事件属性: window.addEventListener(DOMContentLoaded,function(){//因为我们现在使用submit事件,所以我们挂钩了这个事件://使用camelCase获取JavaScript标识符var form = getElem(cookieForm); form.addEventListener (提交,验证); getElem(emailAddress) 。焦点(); //打开花括号应该与它们打开的声明出现在同一行//美元符号是合法的标识符,但通常表示库(如JQuery)和//如果不使用这些库,可能会造成混淆。函数getElem(id){return document.getElementById(id); }函数validate(evt){var inputs = document.querySelectorAll(。validate); //假设为false会更好,这样可以避免false positivesvar isValid = false; //遍历需要验证的字段(var i = 0; i< inputs.length; ++ i){var message =; //这是潜在的错误信息//根据它的id验证输入:switch(inputs [i] .id){casefirstName://你不能用逗号分隔的列表检查单个值,您必须根据您感兴趣的每个值来检查// isValid =(inputs [i] .value!==Cherry&& inputs [i] .value!==Micheal&& inputs [i] .value!==Sandra&&& amp; inputs [i] .value!==Cookie)?假:真;消息=(!isValid)? 这个人不存在。 :;打破; caseorderNumber://记住,HTML表单字段总是返回字符串,而不是数字isValid =(inputs [i] .value!==3134&& inputs [i] .value!==4234& amp ;& inputs [i] .value!==9234&&& amp; inputs [i] .value!==3566)?假:真;消息=(!isValid)? 订单号无效。 :;打破; casedateOfOrder:isValid =(inputs [i] .value!=='12-07-23'&&& inputs [i] .value!== '15-04-24'&& inputs [ i] .value!== '16 -02-01'&&& inputs [i] .value!== '14 -01-12')?假:真;消息=(!isValid)? 系统中不存在日期:;打破; caseemailAddress:isValid =(inputs [i] .value!=cherryjackson@gmail.com&& inputs [i] .value!==michealroberts@yahoo.com&& inputs [i ] .value!==sandrabell@hotmail.com&& inputs [i] .value!==cookiedanny@outlook.com)?假:真;消息=(!isValid)? 电子邮件不存在:;打破; } //用正确的消息更新UI:inputs [i] .nextElementSibling.textContent = message; } if(!isValid){//如果我们无效,取消提交evt.preventDefault(); //取消表单的提交evt.stopPropagation(); //不要冒泡事件}}};

body {background-color:#FBFBE8;} / *告诉HTML5找到我的操作系统所具有的字体类型,然后将它用于标题1,并将第一个标题居中* / h1 {font-family:Arial, Helvetica,sans-serif;文本对齐:中心; } / *如果HTML源文件中的第一段不可用,则告诉HTML5使用任何字体类型。还从段落的左边缘清除了一些空白区域,最后告诉它给该段落20个像素的大小。 * / p {font-family:Arial,Helvetica,sans-serif; padding:20px;字体大小:20像素; } label {float:left;宽度:11em; text-align:right; font-family:Arial,Helvetica,sans-serif;颜色:#800000;} input {margin-left:1em;边距:.5em; } span {color:red; } .field_set_1 {border-color:purple; border-style:solid;}#form_submission {background-color:black;白颜色; } legend {font-family:Arial,Helvetica,sans-serif;颜色:蓝色;} / *所有的类仅用于定位和浮动四个相同的图像输入信息* / Wrap1 {float:right;保证金:40像素;宽度:200像素; height:200px;}。Wrap2 {float:left;保证金:40像素;宽度:200像素; clearfix {clear:both;}

< form id =cookieFormname =cookieFormaction =submit form.htmlmethod =get> < fieldset class =field_set_1> <! - 下方设定表格的标题 - > <图例>客户订单表单信息:< / legend> <! - 创建第一个左标签以指定应在文本框中放置标签右侧的内容。下面的其他部分也是如此。 - > < label for =firstName>名字:< / label> < input type =textid =firstNamename =firstNameclass =validate> < span id =firstname_error> *< / span>< br> < label for =orderNumber>订单号码:< / label> < input type =textid =orderNumbername =orderNumberclass =validate> < span id =orderNumber_error> *< / span>< br> < label for =dateOfOrder>订单日期:< / label> < input type =textid =dateOfOrdername =dateOfOrderclass =validate> < span id =dateOfOrder_error> *< / span>< br> < label for =emailAddress>电子邮件地址:< / label> < input type =textid =emailAddressname =emailAddressclass =validate> < span id =emailAddress_error> *< / span>< br> <标签>&安培; NBSP;< /标签> <! - 始终使用提交按钮启动表单提交,即使会有表单验证 - > < input type =submitid =form_submissionvalue =提交此表单> < / fieldset>< / form>

I am trying to figure out why the form's "submit this form" button is not taking me to another HTML page I specified in the <form ... action="submit form.html" method="get"> attribute and not only that but when I put wrong first names, email addresses, and order numbers, and date of orders, it doesn't return JavaScript messages I specified in my if-else codes using JavaScript.

Here is the JavaScript code I use on the form.

var $ = function (id)
{
  return document.getElementById(id); 
}

var submitForm = function()
{
   var FirstName= $("firstName").value;
   var OrderNumber= $("orderNumber").value; 
   var DateOfOrder= $("date_of_order").value;
   var emailAddress= $("email_address").value; 
   var isValid=true;
    
   if(FirstName !== "Cherry", "Micheal", "Sandra", "Cookie")
   {
      $("firstname_error").firstChild.nodeValue=
       "This person does not exist.";
       isValid=false;
    } else{ $("firstname_error").firstChild.nodeValue="";}
    
  if(OrderNumber !== 3134, 4234, 9234, 3566)
  {
     $("orderNumber_error").firstChild.nodeValue="Invalid Order Number.";
     isValid=false;
   } else{ $("orderNumber_error").firstChild.nodeValue="";}

  if(DateOfOrder !=='12-07-23', '15-04-24', '16-02-01', '14-01-12')
  {
    $("date_of_order_error").firstChild.nodeValue="Date doesn't exist in
    system";
    isValid=false;
  } else{ $("date_of_order_error").firstChild.nodeValue="";}
  
  if(emailAddress !="cherryjackson@gmail.com", "michealroberts@yahoo.com",
   "sandrabell@hotmail.com", "cookiedanny@outlook.com")
  {
    $("email_address_error").firstChild.nodeValue="The email doesn't exist";
     isValid=false;
  } else{ $("email_address_error").firstChild.nodeValue="";}
   if(isValid)
     {
	   //submit the form if all entries are valid
	    $("cookie_form").submit();
     }
}
window.onload = function()
  {
    $("form_submission").onclick = submitForm;	
     $("email_address").focus(); 
  }

body{
       background-color:#FBFBE8;


}
/* Tells HTML5 to find the font-type-face that my OS has and then use that for heading 1
  and also centers the first heading */  
                     
h1{
            font-family:Arial, Helvetica, sans-serif; 
	    text-align:center;        
}


/* Tells HTML5 to use any of the font-types for my first paragraph in HTML source file
   if one is not available. Also clears some white space 
   from the left margin of the paragraph and finally tells it to give that paragraph
   a size of 20 pixels. */

p{
            font-family:Arial, Helvetica, sans-serif; 
            padding: 20px;
            font-size:20px;  
}



label{
	float: left; 
	width: 11em; 
	text-align: right;
        font-family:Arial, Helvetica, sans-serif; 
        color:#800000;

}
  input{
  	  margin-left: 1em; 
  	  margin-bottom:.5em; 
  }
  span{
  	  color: red; 
  }

.field_set_1{
              border-color: purple;
              border-style: solid;


}

#form_submission{
                   background-color:black; color:white;

}

legend{ 
         font-family:Arial, Helvetica, sans-serif; 
          color:blue;
          
          

} 

/* All of the classes are just for positioning and floating the four 
same images around the form input information   */

.Wrap1{
             float:right;
             margin:40px;
             width:200px; 
             height:200px;
}
.Wrap2{
             float:left;
             margin:40px;
             width:200px; 
             height:200px;
}

.clearfix {
  clear: both;
}

<!DOCTYPE html>
<html>
<head>
<title>Cookie Order Form </title>
<link rel="stylesheet" href="First_Design.css">
<script src="cookieform.js"></script>
</head>
<body>
<h1>Cookie Order Form</h1>
<p>This form is a cookie order form for customers that purchased cookies from
Daron's Cookies Company and the following below must be filled out in order for each
customer to receive a final message that tells them when their order will be ready.</p>


<IMG class="Wrap1" SRC="cookie.gif" alt="cookie">
<IMG class="Wrap2" SRC="cookie.gif" alt="cookie2">



<!--The customer will be sent to the HTML page named "submit form.html" after they
  click the "Submit this Form" button. The code below does this. -->
 <div>
 <form id="cookie_form" name="cookie_form" action="submit form.html" method="get">

<fieldset class="field_set_1">
         <!-- Below sets the title of the form-->
    <legend>Customer Order Form Information:</legend> 


 <!-- Creates the first left label to specify what should be placed in the text box
    the the right of the label. The rest below does the same.-->
 
  <label for="firstName">First Name:</label>
  <input type="text" id="firstName" name="firstName">
  <span id="firstname_error">*</span><br>

  <label for="orderNumber">Order Number:</label>
  <input type="text" id="orderNumber" name="orderNumber">
  <span id="orderNumber_error">*</span><br>
  
  <label for="date_of_order">Date of Order:</label>
  <input type="text"  id="date_of_order" name="date_of_order">
  <span id="date_of_order_error">*</span><br>

  <label for="email_address">Email Address:</label>
  <input type="text" id="email_address" name="email_address">
  <span id="email_address_error">*</span><br>

  <label>&nbsp;</label>
  
  <input type="button" id="form_submission" value="Submit this Form">
  </fieldset>

  </form>

</div>
<div class="clearfix">
</div>
<IMG class="Wrap1" SRC="cookie.gif" alt="cookie">
<IMG class="Wrap2" SRC="cookie.gif" alt="cookie2">


</body>



</html>

解决方案

There were a great many things wrong with your code, but the biggest was your validation tests, that each followed the same structure of:

if(FirstName !== "Cherry", "Micheal", "Sandra", "Cookie")

You can't test firstName against a comma-separated list of values. Each one must be tested individually and you must use a compound logical operator between them:

if(FirstName !== "Cherry" && FirstName !== "Micheal" &&
   FirstName !== "Sandra" && FirstName !== "Cookie")

You were also using a standard button, rather than a submit button, which can cause all your validation to be bypassed in some situations when the ENTER key is hit. Always use a submit button and validate in the submit event.

Please see my restructured and re-organized code solution for inline comments.

The Stack Overflow snippet environment (below) doesn't work with forms (because it's sandboxed), but the same code can be run here.

// W3C DOM Event model instead of node event properties:
window.addEventListener("DOMContentLoaded", function() {
  
  // Since we're now using the submit event, we hook into that event:
  // Use camelCase for JavaScript identifiers
  var form = getElem("cookieForm");
  form.addEventListener("submit", validate);	
  
  getElem("emailAddress").focus(); 
  
  // Opening curly braces should appear on the same line as the declaration they open
  // Dollar signs are legal identifiers, but usually denote libraries (like JQuery) and
  // can be confusing if you are not using those libraries.
  function getElem (id) {
    return document.getElementById(id); 
  }

  function validate(evt) {   
    var inputs = document.querySelectorAll(".validate");
  
    // It's better logic to assume false, which avoids "false positives"
    var isValid = false;
    
    // Loop through the fields that need validation
    for (var i = 0; i < inputs.length; ++i){
    
      var message = ""; // This is the potential error message
      
      // Validate the input according to its id:
      switch (inputs[i].id) {
          case "firstName" :
            // You can't check a single value against a comma-separated list, you have to check
            // it against each value you are interested in:
            isValid = (inputs[i].value !== "Cherry" && inputs[i].value !== "Micheal" && 
                       inputs[i].value !== "Sandra" && inputs[i].value !== "Cookie") ? false : true;
            message = (!isValid) ? "This person does not exist." : "";
            break;
          case "orderNumber" :
            // Remember, HTML form fields always return strings, not numbers
            isValid = (inputs[i].value !== "3134" && inputs[i].value !== "4234" && 
                       inputs[i].value !== "9234" && inputs[i].value !== "3566") ? false : true;
            message = (!isValid) ? "Invalid Order Number." : "";
            break;
          case "dateOfOrder" :
            isValid = (inputs[i].value !=='12-07-23' && inputs[i].value !== '15-04-24' && 
                       inputs[i].value !== '16-02-01' && inputs[i].value !== '14-01-12') ? false : true;
            message = (!isValid) ? "Date doesn't exist in system" : "";
            break;
          case "emailAddress" :
            isValid = (inputs[i].value != "cherryjackson@gmail.com" && 
                       inputs[i].value !== "michealroberts@yahoo.com" && 
                       inputs[i].value !== "sandrabell@hotmail.com" && 
                       inputs[i].value !== "cookiedanny@outlook.com") ? false : true;
            message = (!isValid) ? "The email doesn't exist" : "";  
            break;        
      }
      
      // Update the UI with the correct message:
      inputs[i].nextElementSibling.textContent = message;
    }
  
    if(!isValid) {
	    // cancel the submission if we're invalid
	    evt.preventDefault();  // Cancel the form's submission
      evt.stopPropagation(); // Don't bubble the event
    }
  }
  
});

body{
       background-color:#FBFBE8;
}

/* Tells HTML5 to find the font-type-face that my OS has and then use that for heading 1
  and also centers the first heading */  

h1{
  font-family:Arial, Helvetica, sans-serif; 
  text-align:center;        
}


/* Tells HTML5 to use any of the font-types for my first paragraph in HTML source file
   if one is not available. Also clears some white space 
   from the left margin of the paragraph and finally tells it to give that paragraph
   a size of 20 pixels. */

p {
  font-family:Arial, Helvetica, sans-serif; 
  padding: 20px;
  font-size:20px;  
}

label{
	float: left; 
	width: 11em; 
	text-align: right;
        font-family:Arial, Helvetica, sans-serif; 
        color:#800000;

}
  
input{
  	  margin-left: 1em; 
  	  margin-bottom:.5em; 
}



span {
  	  color: red; 
}

.field_set_1{
              border-color: purple;
              border-style: solid;
}

#form_submission{ background-color:black; color:white; }

legend{ 
   font-family:Arial, Helvetica, sans-serif; 
   color:blue;
} 

/* All of the classes are just for positioning and floating the four 
same images around the form input information   */

.Wrap1{
             float:right;
             margin:40px;
             width:200px; 
             height:200px;
}
.Wrap2{
             float:left;
             margin:40px;
             width:200px; 
             height:200px;
}

.clearfix {
  clear: both;
}

<form id="cookieForm" name="cookieForm" action="submit form.html" method="get">

  <fieldset class="field_set_1">
    <!-- Below sets the title of the form-->
    <legend>Customer Order Form Information:</legend> 


    <!-- Creates the first left label to specify what should be placed in the text box
         the the right of the label. The rest below does the same.-->
 
    <label for="firstName">First Name:</label>
    <input type="text" id="firstName" name="firstName" class="validate">
    <span id="firstname_error">*</span><br>

    <label for="orderNumber">Order Number:</label>
    <input type="text" id="orderNumber" name="orderNumber" class="validate">
    <span id="orderNumber_error">*</span><br>
  
    <label for="dateOfOrder">Date of Order:</label>
    <input type="text"  id="dateOfOrder" name="dateOfOrder" class="validate">
    <span id="dateOfOrder_error">*</span><br>

    <label for="emailAddress">Email Address:</label>
    <input type="text" id="emailAddress" name="emailAddress" class="validate">
    <span id="emailAddress_error">*</span><br>

    <label>&nbsp;</label>
  
    <!-- Always use a "submit" button to initiate form submission, even
         if there will be form validation                                 -->
    <input type="submit" id="form_submission" value="Submit this Form">
  </fieldset>

</form>

这篇关于为什么当我点击它时,我的表单提交按钮不会进入下一页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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