验证表单而不重新加载页面

时间:2015-05-19 22:54:52

标签: javascript html

我正在实施一个简单的注册表格。我想验证用户是否选择了至少一个checkbox。除了这一个输入字段之外,我的表单中的所有字段都在验证而没有页面重新加载。当我尝试验证此字段时,页面将重新加载,并且用户先前输入的所有值都将丢失。我想防止这种情况发生。

    function validate() {

	var checkbox1 = document.getElementById('three').checked;
	var checkbox2 = document.getElementById('four').checked;
	var checkbox3 = document.getElementById('five').checked;
	var checkbox4 = document.getElementById('six').checked;

	if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == true) {
		if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
			alert("Please enter all the required values");
		} 
	} 

	if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
		if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
			alert("Please enter all the required values");
		} 
	} 

	if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
		if (referenceToForm.elements["usrgrp[]"].selectedIndex != -1) {
			alert("Please enter all the required values");
		}  
	} 

	if (document.getElementById('values').value == -1) {
		alert("Please enter all the required values checkbox");
	}
}
@import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");

#labels{
	position: relative;
	width: 250px;
	float: left;
}

h3{
	margin: 0px 0px 20px 0px;
}

#fields{
	position: relative;
	width: 250px;
	float: left;
}

.element{
	margin-bottom: 23px;
	border: 1px solid #dadada;
	border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

.different{
	margin-top: 4px;
	margin-bottom: 22px;
}

.values{
	margin-bottom: 23px;
}

.heading, .feedback{
	margin-top: 43px;
}

.preference{
	border-color:  #06a3e9;
	box-shadow: 0 0 1px lightblue;
}

.multiple{
	border-color:  #06a3e9;
	box-shadow: 0 0 1px lightblue;
	margin-top: 20px;
}

textarea{
	margin-top: 20px;
	border: 1px solid  #06a3e9;
	box-shadow: 0 0 1px lightblue;
}

a{
	color: #06a3e9;
}

.final{
	margin-top: 15px;
}

.feedback{
	margin-top: 73px;
}

#submit, #reset{
	border: 1px solid #dadada;
	border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    border-radius:5px;
}

input[type="checkbox"]{
	display: none;
}

label:before{
	width: 1em;
	display: inline-block;
}

label{
	margin-right: 5px;
}

input[type="checkbox"] + label:before{
	font-family: FontAwesome;
  	display: inline-block;
  	content: "\f096";
  	letter-spacing: 5px;
  	color: #06a3e9;
  	display: inline-block;
}

input[type="checkbox"]:checked + label:before{
	content:"\f14a";
	display: inline-block;
	color: #06a3e9;
}

input[type="radio"]{
	display: none;
}

input[type="radio"] + label:before{
	font-family: FontAwesome;
  	display: inline-block;
  	content:"\f10c";
  	font-size: 14px;
  	color: #06a3e9;
  	letter-spacing: 5px;
  	display: inline-block;
}

input[type="radio"]:checked + label:before{
	content:"\f192";
	font-size: 14px;
	display: inline-block;
}
<!doctype html>
<html>

  <head>
    <title> Register here </title>
    <link rel="stylesheet" href="../css/registration.css"/>
    <script src = "../javascript/registration.js"></script>
  </head>

  <body>
        <h1>Event Registration Form</h1>

        <div id="labels">
            <h3>Username</h3>
            <h3>Password</h3>
            <h3>Age</h3>
            <h3>Email</h3>
            <h3>Existing customer?</h3>
            <h3>Select your preferences</h3>
            <h3>Newsletter Preferences</h3>
            <h3 class="heading">Menu Options</h3>
            <h3 class="feedback">Send us your feedback !</h3>
        </div>

        <div id="fields">
            <form action="#" method="get" name="referenceToForm">
                <input type="text" name="Username" id="Username" class="element"required/>
                <input type="password" name="Password" class="element" required/>
                <input type="number" name="Age" class="element" required/>
                <input type="email" name="Email" class="element" required/>

            <div class="different">
              <input type="radio" name="customer" id="one" checked="checked" />
              <label for="one">Yes</label>
              <input type="radio" name="customer" id="two" />
              <label for="two">No</label>
            </div>

            <div class="values">
              <input type="checkbox" name="interest" id="three" />
              <label for="three">Dog</label>
              <input type="checkbox" name="interest" id="four" />
              <label for="four">Cat</label>
              <input type="checkbox" name="interest" id="five" />
              <label for="five">Parrot</label>
              <input type="checkbox" name="interest" id="six" />
              <label for="six">Possum</label>
              <span id="spanning"> </span>
            </div>

            <select class="preference" id="preference" value="-1">
                <option value="Entertainment">Entertainment</option>
                <option value="Technology">Technology</option>
                <option value="TV">TV</option>
            </select>
        
            <div class="menu">
                <select multiple required id="multiple" class="multiple" value="-1" name="usrgrp[]">
                    <option value="Sports">Sports</option>
                    <option value="Politics">Politics</option>
                    <option value="News">News</option>
                    <option value="Swimming">Swimming</option>
                    <option value="Health">Health</option>
                </select>
            </div>
        
            <textarea rows="5" cols="20" required></textarea>
        
            <div class="final">
                <input type="submit" name="submit" id="submit" onclick="validate()" />
                <input type="reset" name="reset" id="reset" />
            </div>
      </form>
    </div>
  </body>
</html>

更新

感谢所有试图帮助我的人。下面是完美解决我的问题的代码。

<!doctype html>
<html>

  <head>
    <title> Register here </title>
    <link rel="stylesheet" href="../css/registration.css"/>
    <script src = "../javascript/registration.js"></script>
  </head>

  <body>
        <h1>Event Registration Form</h1>

        <div id="labels">
            <h3>Username</h3>
            <h3>Password</h3>
            <h3>Age</h3>
            <h3>Email</h3>
            <h3>Existing customer?</h3>
            <h3>Select your preferences</h3>
            <h3>Newsletter Preferences</h3>
            <h3 class="heading">Menu Options</h3>
            <h3 class="feedback">Send us your feedback !</h3>
        </div>

        <div id="fields">
            <form action="#" method="get" name="referenceToForm">
                <input type="text" name="Username" id="Username" class="element"required/>
                <input type="password" name="Password" class="element" required/>
                <input type="number" name="Age" class="element" required/>
                <input type="email" name="Email" class="element" required/>

            <div class="different">
              <input type="radio" name="customer" id="one" checked="checked" />
              <label for="one">Yes</label>
              <input type="radio" name="customer" id="two" />
              <label for="two">No</label>
            </div>

            <div class="values">
              <input type="checkbox" name="interest" id="three" />
              <label for="three">Dog</label>
              <input type="checkbox" name="interest" id="four" />
              <label for="four">Cat</label>
              <input type="checkbox" name="interest" id="five" />
              <label for="five">Parrot</label>
              <input type="checkbox" name="interest" id="six" />
              <label for="six">Possum</label>
              <span id="spanning"> </span>
            </div>

            <select class="preference" id="preference" value="-1">
                <option value="Entertainment">Entertainment</option>
                <option value="Technology">Technology</option>
                <option value="TV">TV</option>
            </select>

            <div class="menu">
                <select multiple required id="multiple" class="multiple" value="-1" name="usrgrp[]">
                    <option value="Sports">Sports</option>
                    <option value="Politics">Politics</option>
                    <option value="News">News</option>
                    <option value="Swimming">Swimming</option>
                    <option value="Health">Health</option>
                </select>
            </div>

            <textarea rows="5" cols="20" required></textarea>

            <div class="final">
                <input type="submit" name="submit" id="submit" onclick="return validate()" />
                <input type="reset" name="reset" id="reset" />
            </div>
      </form>
    </div>
  </body>
</html>  

CSS

@import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");

#labels{
    position: relative;
    width: 250px;
    float: left;
}

h3{
    margin: 0px 0px 20px 0px;
}

#fields{
    position: relative;
    width: 250px;
    float: left;
}

.element{
    margin-bottom: 23px;
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

.different{
    margin-top: 4px;
    margin-bottom: 22px;
}

.values{
    margin-bottom: 23px;
}

.heading, .feedback{
    margin-top: 43px;
}

.preference{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

.multiple{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    margin-top: 20px;
}

textarea{
    margin-top: 20px;
    border: 1px solid  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

a{
    color: #06a3e9;
}

.final{
    margin-top: 15px;
}

.feedback{
    margin-top: 73px;
}

#submit, #reset{
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    border-radius:5px;
}

input[type="checkbox"]{
    display: none;
}

label:before{
    width: 1em;
    display: inline-block;
}

label{
    margin-right: 5px;
}

input[type="checkbox"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content: "\f096";
    letter-spacing: 5px;
    color: #06a3e9;
    display: inline-block;
}

input[type="checkbox"]:checked + label:before{
    content:"\f14a";
    display: inline-block;
    color: #06a3e9;
}

input[type="radio"]{
    display: none;
}

input[type="radio"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content:"\f10c";
    font-size: 14px;
    color: #06a3e9;
    letter-spacing: 5px;
    display: inline-block;
}

input[type="radio"]:checked + label:before{
    content:"\f192";
    font-size: 14px;
    display: inline-block;
}

的JavaScript

function validate() {



var checkbox1 = document.getElementById('three').checked;
    var checkbox2 = document.getElementById('four').checked;
    var checkbox3 = document.getElementById('five').checked;
    var checkbox4 = document.getElementById('six').checked;

    if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
            alert("Please enter all the required values");
            return false;
    } 
}

2 个答案:

答案 0 :(得分:1)

我发现您的表单存在两个问题,而且两者都很容易修复。

您的验证功能必须返回true以提交表单,或返回false以取消。如果您没有提供返回值(如代码中那样),则始终会提交表单:

<input type="submit" name="submit" id="submit" onclick="validate()" >

要修复此问题,您需要让验证函数返回一个返回给onclick处理程序的值:

<input type="submit" name="submit" id="submit" onclick="return validate()" >

验证函数中的这一行会抛出错误,因为没有id =“values”的元素。您需要删除或修复此代码,以便您的函数正常完成并返回true或false值。

if (document.getElementById('values').value == -1) {
    alert("Please enter all the required values checkbox");
}

也许有人可以就此发表评论,但我总是看到以onsubmit事件的形式而不是提交按钮onclick事件处理验证。然而,也许这只是惯例,因为它似乎以任何一种方式起作用:

<form onsubmit="return validate()" ...

<input type="submit" onclick="return validate()" ...

答案 1 :(得分:0)

如果你使用jsFiddle,最重要的是使用这种初始化函数的方法:

window.validate = function() {

而不是这样:

function validate() {

这是我的捅。没有Angular,也没有使用JQuery,尽管我建议学习它们。我搞砸了你的提交按钮,但很容易用css修复。我还添加了一个假提交按钮,仅触发验证。如果通过验证,则可以继续发送。我的jsfiddle:

http://jsfiddle.net/omikey/tfk7d3ks/

<div class="container">
 <div id="labels">
        <h3>Username </h3>
        <h3>Password</h3>
        <h3>Age</h3>
        <h3>Email</h3>
        <h3>Existing customer?</h3>
        <h3>Select your preferences</h3>
        <h3>Newsletter Preferences</h3>
        <h3 class="heading">Menu Options</h3>
        <h3 class="feedback">Send us your feedback !</h3>
     </div>

    <div id="fields">
      <form action="#" method="get" name="referenceToForm">
        <div>
          <input type="text" name="Username" id="Username" class="element" required/>
        </div>
        <div>
          <input type="password" name="Password" class="element" required/>
        </div>
        <div>
          <input type="number" name="Age" class="element" required/>
        </div>
        <div>
          <input type="email" name="Email" class="element" required/>
        </div>
        <div class="different">
          <input type="radio" name="customer" id="one" checked="checked" />
          <label for="one">Yes</label>
          <input type="radio" name="customer" id="two" />
          <label for="two">No</label>
        </div>

        <div class="value">
          <input type="checkbox" name="interest" id="three" />
          <label for="three">Dog</label>
          <input type="checkbox" name="interest" id="four" />
          <label for="four">Cat</label>
          <input type="checkbox" name="interest" id="five" />
          <label for="five">Parrot</label>
          <input type="checkbox" name="interest" id="six" />
          <label for="six">Possum</label>
          <span id="spanning"> </span>
        </div>

        <div>
          <select class="preference" id="preference" value="-1">
            <option value="Entertainment">Entertainment</option>
            <option value="Technology">Technology</option>
            <option value="TV">TV</option>
          </select>
        </div>

        <div class="menu">
          <select multiple id="multiple" class="multiple" value="-1" name="usrgrp[]">
            <option value="Sports">Sports</option>
            <option value="Politics">Politics</option>
            <option value="News">News</option>
            <option value="Swimming">Swimming</option>
            <option value="Health">Health</option>
          </select>
          <span id="spanElement"> </span>
        </div>

        <div class="comment">
          <textarea rows="5" cols="20" required></textarea>
        </div>

        <div class="final">
            <input type="button" name="verify" onclick="validate()" />
          <input type="submit" name="submit" style="display:none" id="submit" />
          <input type="reset" name="reset" id="reset" />
        </div>
      </form>
    </div>
</div>
    @import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");

.container{
    width: 100%;
    margin-left: 400px;
}

#spanning{
    color: #06a3e9;
}

.nav ul{
    width: 150px;
    float: left;
    background-color: #dadada;
    padding: 0px;
    margin: 0px;
}

.nav li{
    list-style-type: none;
}

.nav a{
    color:#000;
    cursor:pointer;
    display: block;
    line-height: 40px;
    text-indent: 10px;
    text-decoration: none;
    font-weight: bold;
}

.nav ul ul li{
    display: none;
}

.nav li:hover ul li{
    display: block;
}

.subnav ul{
    position: relative;
    background: #dadada;

}

#labels{
    position: relative;
    width: 250px;
    top:80px;
    float: left;
}

h3{
    margin: 0px 0px 20px 0px;
}

#fields{
    position: relative;
    width: 250px;
    top:80px;
    float: left;
}

.element{
    margin-bottom: 23px;
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

.different{
    margin-top: 4px;
    margin-bottom: 22px;
}

.value{
    margin-bottom: 23px;
}

.heading, .feedback{
    margin-top: 43px;
}

.preference{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

.multiple{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    margin-top: 20px;
}

textarea{
    margin-top: 20px;
    border: 1px solid  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

a{
    color: #06a3e9;
}

.final{
    margin-top: 15px;
}

.feedback{
    margin-top: 73px;
}

#submit, #reset{
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    border-radius:5px;
}

input[type="checkbox"]{
    display: none;
}

label:before{
    width: 1em;
    display: inline-block;
}

label{
    margin-right: 5px;
}

input[type="checkbox"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content: "\f096";
    letter-spacing: 5px;
    color: #06a3e9;
    display: inline-block;
}

input[type="checkbox"]:checked + label:before{
    content:"\f14a";
    display: inline-block;
    color: #06a3e9;
}

input[type="radio"]{
    display: none;
}

input[type="radio"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content:"\f10c";
    font-size: 14px;
    color: #06a3e9;
    letter-spacing: 5px;
    display: inline-block;
}

input[type="radio"]:checked + label:before{
    content:"\f192";
    font-size: 14px;
    display: inline-block;
}

    window.validate = function() {

    var valid = true;

  var checkbox1 = document.getElementById('three').checked;
  var checkbox2 = document.getElementById('four').checked;
  var checkbox3 = document.getElementById('five').checked;
  var checkbox4 = document.getElementById('six').checked;

  if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == true) {
    if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
      alert("Please enter all the required values");
        valid = false;
    }
  }
  if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
    if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
      alert("Please enter all the required values");
        valid = false;
    }
  }
  if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
    if (referenceToForm.elements["usrgrp[]"].selectedIndex != -1) {
      alert("Please enter all the required values");
        valid = false;
    }
  }    

    if (document.getElementById('multiple').value == -1)
    {
      alert("Please enter all the required values");
        valid = false;
    }

    if (document.getElementById('preference').value == -1)
    {
      alert("Please enter all the required values");
        valid = false;
    }

    if (valid)
    {
        document.getElementById('submit').click();
    }
}