我的所有其他字段都按我的要求进行了验证,但是当我添加JS来验证选择选项时,我的页面会在重新提交后重新加载。我尝试了多种方法来使选择选项生效,但是我没有找到解决方案。根据项目要求,我必须使用普通的JS来验证整个表单,并且我在不包含任何用户输入的范围内的每个字段下方显示错误消息。我将在下面发布我的JS,并且可以在需要时发布我的HTML。我在选择的区号之间添加了一些额外的空格,以期提高可读性。
document.addEventListener("DOMContentLoaded", function (event) {
alert("This page is best viewed with JavaScript enabled");
});
function validate() {
// NEW: move this way up here so all validations can affect its value:
var formValid = true;
// function to check if a name has been entered
var name = document.getElementById('name').value;
if (name == null || name.trim() == "") {
document.getElementById('nameerror').innerHTML = "Please enter your full name";
formValid = false;
} else {
document.getElementById('nameerror').innerHTML = "";
}
// function to check if an email has been entered
var email = document.getElementById('email').value;
if (email == null || email.trim() == "") {
document.getElementById('emailerror').innerHTML = "Please enter your email address";
formValid = false;
} else {
document.getElementById('emailerror').innerHTML = "";
}
// function to check if a telephone number has been provided
var phone = document.getElementById('phone').value;
if (phone == null || phone.trim() == "") {
document.getElementById('phoneerror').innerHTML = "Please enter your telephone number";
formValid = false;
} else {
document.getElementById('phoneerror').innerHTML = "";
}
//validate the select options
var select = document.getElementById('select').value;
if (select == '') {
document.getElementById('selecterror').innerHTML = "Please make a selection";
formValid = false;
} else {
document.getElementById('selecterror').innerHTML = "";
}
//function to validate the textarea field
var name = document.getElementById('textarea').value;
if (name == null || name.trim() == "") {
document.getElementById('textareaerror').innerHTML = "Please enter additional info";
formValid = false;
} else {
document.getElementById('textareaerror').innerHTML = "";
}
// function to validate if any radio button has been selected
var radios = document.getElementsByName('radio');
var radiosValid = false;
var i = 0;
while (!radiosValid && i < radios.length) {
if (radios[i].checked) radiosValid = true;
i++;
}
if (!radiosValid) {
document.getElementById('radioerror').innerHTML = "(Please check one)";
formValid = false;
} else {
document.getElementById('radioerror').innerHTML = "";
}
// function to confirm if any checkbox has been checked
var checkboxes = document.getElementsByName('checkbox');
var checkboxesValid = false;
var j = 0;
while (!checkboxesValid && j < checkboxes.length) {
if (checkboxes[j].checked) checkboxesValid = true;
j++;
}
if (!checkboxesValid) {
document.getElementById('checkboxerror').innerHTML = "(Please select at least one)";
formValid = false;
} else {
document.getElementById('checkboxerror').innerHTML = "";
}
// now that all validations have run, return the conclusion
alert("The form has been submitted!");
return formValid;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact Us</title>
<style>
.contact-header {
font-family: cursive;
text-align: center;
font-size: 50px;
color: darkred;
}
form {
font-weight: bold;
text-align: center;
}
.contact {
font-weight: normal;
}
.checkbox input {
margin: 0 10px 0;
}
textarea {
width: 20%;
height: 5rem;
}
.sendRequest {
text-align: center;
}
</style>
<!--link to bootstrap css-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!--link for icons-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<!--link to external stylesheet-->
<link href="restaurantStyles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<header>
<div class="jumbotron name-font">
<h1 class="display-4">Dan's Cakes</h1>
<hr class="my-4">
<p class="lead">BIG NEWS!! Dan's Cakes will be opening a new restaurant VERY soon!!!!</p>
</div>
</header>
<hr />
<nav>
<!--home icon link-->
<a href="index.html" class="btn badge-pill"><i class="fas fa-home"></i></a>
<a href="menu.html" class="btn badge-pill">Menu</a>
<a href="contact.html" class="btn badge-pill">Contact Us</a>
</nav>
<hr />
<h2 class="contact-header">Contact Us</h2>
<hr />
<!--form for contact info-->
<form name="contactForm" method="post" id="contactForm" novalidate onsubmit="return validate()">
<div class="form-group col-form-label">
<label for="name">Name: </label>
<input type="text" class="form-control" id="name" placeholder="Please enter your full name.." required>
<span id="nameerror" class="hint"></span>
</div>
<div class="form-group">
<label for="email">Email: </label>
<i class="fas fa-envelope prefix"></i>
<input type="email" class="form-control" id="email" placeholder="Please enter your email address.." aria-describedby="email" required>
<span id="emailerror" class="hint"></span>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="phone">Phone: </label>
<i class="fas fa-phone-square"></i>
<input type="tel" class="form-control" id="phone" required>
<span id="phoneerror" class="hint"></span>
</div>
<!--select menu-->
<label for="reason-select">Reason For Inquiry:</label>
<select id="select " name="reason" class="custom-select" required>
<option value="">--Please Choose an Option--</option>
<option value="catering">Catering</option>
<option value="private">Private Party</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<span id="selecterror" class="hint"></span>
<br />
<br />
<!--text area for additional info-->
<div class="form-group">
<label for="info">Additional Information: </label>
<textarea class="form-control" id="textarea" rows="5"></textarea>
<span id="textareaerror" class="hint"></span>
</div>
<!--radio buttons for visiting restaurant-->
<label for="radio">Have you been to the restaurant?</label>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="radio" id="no-radio" value="no">
<label class="form-check-label" for="no-radio">
No
</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="radio" id="yes-radio" value="yes">
<label class="form-check-label" for="yes-radio">
Yes
</label>
<span id="radioerror" class="hint"></span>
</div>
<br />
<!--checkboxes for contacting-->
<label for="checkboxes">Best days to contact you:</label>
<div id="checkboxlist">
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="monday" value="monday">
<label class="form-check-label" for="monday">M</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="tuesday" value="tuesday">
<label class="form-check-label" for="tuesday">T</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="wednesday" value="wednesday">
<label class="form-check-label" for="wednesday">W</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="thursday" value="thursday">
<label class="form-check-label" for="thursday">Th</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="friday" value="friday">
<label class="form-check-label" for="friday">F</label>
</div>
<span id="checkboxerror" class="hint"></span>
</div>
<!--send request button-->
<div class="sendRequest" id="contact-submit">
<input type="submit" value="Send Request">
</div>
</form>
<br />
<br />
<footer>
<p>1123 Silk Way, Anchorage, AK, 99501</p>
<p>907-998-0122</p>
</footer>
</div>
<script>
document.contactForm.name.onfocus = function () {
document.getElementById('namehint').innerHTML = "(Enter full name)";
}
</script>
<!--scripts for jquery, popper, and bootstrap-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<!--javascript link to external sheet-->
<script src="validate.js"></script>
<!--<script>
document.contactForm.name.onfocus = function () {
document.getElementById('namehint').innerHTML = "(Enter full name)";
}
</script>
-->
</body>
</html>
答案 0 :(得分:1)
使用提交按钮时,其默认设置是刷新或将您定向到在定义表单html标签时在action
属性中指定的位置。如果您的目标是停止刷新,则需要在按钮上放置一个onClick
属性,该按钮包含要执行的功能(如果您知道将事件侦听器放置在DOM元素上的任何其他方法,则可以采用该方法同样,我只是以此为例),然后您将传递一个变量event
来将事件操作保存到参数中。然后在函数中使用event.preventDefault();
,这将停止刷新。执行该命令后,您可以执行任何其他验证操作,然后触发刷新或新窗口位置,这是您的目标。
答案 1 :(得分:0)
您遇到的第一个问题是您正在做的事情:
var select = document.getElementById('select').value;
但是选择是这样声明的:
<select id="select " name="reason" class="custom-select" required>
它的ID为"select "
,因此您将得到TypeError
的信息,说您无法从value
读取undefined
。它只是一个错字,但错别字!只需删除这样的尾随空格即可:
<select id="select" name="reason" class="custom-select" required>
我认为这应该可以解决您的问题。此外,如果要阻止页面重新加载,无论表单是否有效,都必须防止提交动作的默认行为。您可以通过在Submit事件上调用preventDefault
来做到这一点,这将需要传递给函数。请记住,这样就永远不会提交表单,您将必须自己完成。
通过以下方式将事件传递到函数validate
:
<form name="contactForm" method="post" id="contactForm" novalidate onsubmit="return validate(event)">
...
</form>
并防止默认行为:
function validate(e) {
e.preventDefault();
... // The rest of your code
}
Here是preventDefault
让我知道这是否对您有帮助,否则,请告诉我出了什么问题。