The files are in the the correct locations, both the form page and form complete page are in the same folder. When I click submit, it validates the form correctly, but if everything is entered correctly and validates, it does nothing, just takes away the asterisks like it's supposed to in the js. I want it to link to the form_complete.html page after you hit submit and the validation runs, but after it validates nothing happens,
The html:
<form id="contactform" action="form_complete.html" method="post">
<p class = "labelp">
<label for="name">Name: </label>
<input type="text" name="name" id="name" placeholder="Enter your name" >
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="age">Age: </label>
<input type="text" min="18" max="100" name="age" id="age" placeholder="Enter your age">
<!-- using type=text so I can practice isNaN in js -->
<span>*</span><br><br>
</p>
<p class = "labelp"></p>
<label for="country">Country: </label>
<select name="country" id="country">
<option value ="">Select a country</option>
<option>USA</option>
<option>Canada</option>
<option>Mexico</option>
<option>Brazil</option>
<option>Japan</option>
<option>China</option>
<option>Other</option>
</select>
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="email">E-mail: </label>
<input type="email" name="email" id="email" placeholder="Enter your E-mail">
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="bday">Birthday: </label>
<input type="date" name="bday" id="bday">
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="gender" id="gender">Gender: </label>
<input type="radio" name="gender" value="male" id="male"> Male
<input type="radio" name="gender" value="female" id="female"> Female
<input type="radio" name="gender" value="other" id="other"> Other
<br><br>
</p>
<label>Comments: </label>
<textarea rows="5" cols="30"> </textarea><br><br>
<input type="button" id="registerbtn" value="Submit">
<input type="button" id="resetbtn" value="Reset">
</form>
The javascript:
"use strict";
var $ = function(id) { return document.getElementById(id);};
var processEntries = function(){
var isValid = true;
// values
var name = $("name").value;
var age = $("age").value;
var country = $("country").value;
var email = $("email").value;
var bday = $("bday").value;
var gender = "";
if ($("male").checked){gender = "Male";}
if ($("female").checked){gender = "Female";}
if ($("other").checked){gender = "Other";}
console.log(gender); //check if gender buttons work
// name
if(name == ""){
$("name").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("name").nextElementSibling.firstChild.nodeValue = "";
}
// age
if(age == ""){
$("age").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;
}
else if(isNaN(age)){
$("age").nextElementSibling.firstChild.nodeValue = "This field must be a number!";
isValid = false;
}
else{
$("age").nextElementSibling.firstChild.nodeValue = "";
}
//country
if(country == ""){
$("country").nextElementSibling.firstChild.nodeValue = "Please select a country!";
isValid = false;}
else{
$("country").nextElementSibling.firstChild.nodeValue = "";
}
//email
if(email == ""){
$("email").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("email").nextElementSibling.firstChild.nodeValue = "";
}
//birthday
if(bday == ""){
$("bday").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("bday").nextElementSibling.firstChild.nodeValue = "";
}
}
var resetForm = function(){
$("contactform").reset();
$("name").nextElementSibling.firstChild.nodeValue = "*";
$("age").nextElementSibling.firstChild.nodeValue = "*";
$("country").nextElementSibling.firstChild.nodeValue = "*";
$("email").nextElementSibling.firstChild.nodeValue = "*";
$("bday").nextElementSibling.firstChild.nodeValue = "*";
}
window.onload = function() {
$("registerbtn").onclick = processEntries;
$("resetbtn").onclick = resetForm;
$("name").focus();
}
Please put below condition at the end of "processEntries" function
if(isValid){
$("#contactform").submit();
}
Related
This is my html code that I am trying to create the exception handling for. I am trying to create the exceptions for the first form in this code.
<form id="survey" name="survey" method="post">
<div id="errorText"></div>
<fieldset class="labelfloatleft" id="contactinfo"><legend>Your Thoughts</legend>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<label for="emailaddress">Email Address</label>
<input type="email" name="emailaddress" id="emailaddress"
size="30" placeholder="foryou#yahoo.com" />
</fieldset>
<fieldset><legend>Best Movie</legend>
<input type="radio" name="movie" id="horror" value="horror" checked="checked"/>
<label for="horror">The Horror</label>
<input type="radio" name="movie" id="badabing" value="badabing" />
<label for="badabing">Bada-Bing Bada-Boom</label>
<input type="radio" name="movie" id="roll" value="roll" />
<label for="roll">Roll or Die</label>
</fieldset>
<fieldset><legend>Comments</legend>
<label for="message">Your Opinion</label>
<textarea name="message" id="message" rows="7" cols="30"></textarea>
</fieldset>
<input type="submit" value="Send" class="button" id="submitBtn"/>
<input type="reset" value="Cancel" class="button" />
</form>
<h2>Welcome To Our World</h2>
<p class="very">We are a small time movie theater looking to help inspire
people who come to our theater. Our theaters come with
fresh food, cold and hot drinks, souvenirs and comfortable
seats to help make your experience worth while.
</p>
<h2>Most Popular</h2>
<ul>
<li>The Horror</li>
<li>Bada-Bing Bada-Boom</li>
<li>Roll or Die</li>
</ul>
<h2>Prices</h2>
<table title="prices">
<tr>
<th>Ticket</th>
<th>Price</th>
<th>Thursday Deal</th>
</tr>
<tr>
<td>Adult</td>
<td>$10.00</td>
<td rowspan="3">Half-Off</td>
</tr>
<tr>
<td>Child</td>
<td>$6.00</td>
</tr>
<tr>
<td>Senior</td>
<td>$8.00</td>
</table>
<form id="price" name="price" method="post">
<fieldset><legend>Ticket Quantity</legend>
<label for="adultinput">Adult 15-60
<input type="text" id="adultinput" value="1" size="2"/>
</label>
<label for="childinput">Child 1-14
<input type="text" id="childinput" value="0" size="2"/>
</label>
<label for="seniorinput">Senior 50 and up
<input type="text" id="seniorinput" value="0" size="2"/>
</label>
</fieldset>
<input type="submit" value="Calculate" id="calculate" class="button" />
<input type="reset" value="Cancel" class="button" />
</form>
This is my exception handling code that I am trying to get working. However, no matter how much I modify it, it never shows correctly. I have ran it in Chrome and have tried using a debugger to help however I am still unable to show the exceptions when I click the submit button.
"use strict";
var fnameComplete = true;
var lnameComplete = true;
var emailComplete = true;
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
var errorDiv = document.getElementById("errorText");
function verifyFname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(fname.value)) || (fname.value === "")){
fname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
fnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyLname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(lname.value)) || (lname.value === "")){
lname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
errorDiv.style.display = "block";
lnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyEmail() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(email === "") {
email.style.background = "rgb(255,233,233)";
throw "Please enter your email.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
emailComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function validateForm(e) {
if (e.preventDefault) {
e.preventDefault(); //prevent form from submitting
} else {
e.returnValue = false; //prevent form from submitting in IE8
}
formValidity = true; //reset value for revalidation
verifyEmail();
verifyFname();
verifyLname();
if(formValidity === true) {
document.getElementsByTagName("form")[0].submit();
}
}
function createEventListeners() {
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener){
form.addEventListener("submit", validateForm, false);
} else if(form.attachEvent) {
form.attachEvent("onsubmit", validateForm);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
} else if(window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
It looks like you try to access a non existing field.
Here you already get the values of the fields
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
And in your comparisons you try to access a value field again. But you already have the plain value
if(!(isNaN(lname.value)) || (lname.value === "")){
}
Do it this way instead
if(!(isNaN(lname)) || (lname === "")){
}
I currently trying to make a website with a validating booking form for a university a project about a university portal. It used to work with my javascript validation until I added to validate time. Problem is sumbit button not working when I add to validate time and whenever I remove it is working.
HTML and JavaScript
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Any suggestions?
You should do this kind of thing with required.
<input type="email" required>
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
(https://www.w3schools.com/tags/att_input_required.asp)
There also exist pattern. For example, if you want to allow only six letters
<input type="text" pattern="[A-Za-z]{6}" required>
Here's a stackoverflow question that gives more information.
As i can see, the problem isn't on validateDate but on validateWorkshop. If you try to submit a blank form, without choosing a workshop, reason.length gets value 5. But if you pick a workshop, reason.length gets 13.
Not that i recomend your validation but to get this working, i just added a var error = ""; at the begining of validateWorkshop.
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
var error = "";
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
On the 82 line of my JavaScript I have "document.getElementById("errors").innerHTML = errMsg;" this code and I was wondering how to implement it into my HTML page so when the validation isn't correct the error message will be displayed in the correct place such as when someone is younger then 15 the error message will be displayed next to date of birth. At the moment I have my errors appearing in an alert but I'd like them to appear on the web page. I also when to know if my "storeForm" and "prefillForm" functions are correct because I tried to test them and it doesn't seem to work. How do I go about fixing these?
"use strict";
/*get variables from form and check rules*/
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
//var JobID = document.getElementById("JobID").value;
var firstName = document.getElementById("firstName").value;
var familyName = document.getElementById("familyName").value;
var midName = document.getElementById("midName").value;
var male = document.getElementById("male").checked;
var female = document.getElementById("female").checked;
var street = document.getElementById("street").value;
var suburb = document.getElementById("suburb").value;
var state = document.getElementById("state").options[document.getElementById("state").selectedIndex].text;
var postcode = document.getElementById("postcode").value;
var email = document.getElementById("email").value;
var number = document.getElementById("number").value;
var XML = document.getElementById("XML").checked;
var Java = document.getElementById("Java").checked;
var Python = document.getElementById("Python").checked;
var SQL = document.getElementById("SQL").checked;
var PERL = document.getElementById("PERL").checked;
var MySQL = document.getElementById("MySQL").checked;
var Windows = document.getElementById("Windows").checked;
var UNIX = document.getElementById("UNIX").checked;
var Linux = document.getElementById("Linux").checked;
var other = document.getElementById("other").checked;
var otherText = document.getElementById("otherText").value;
var dob = document.getElementById("dob").value.split("/");
var date = new Date(dob[2], parseInt(dob[1]) - 1, dob[0]);
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
//get varibles from form and check rules here
// if something is wrong set result = false, and concatenate error message
if (age >= 80) { // Outside age ranges.
errMsg = errMsg + "You must be 80 or younger to apply for this job\n";
result = false;
}
if (age <= 15) { // Outside age ranges.
errMsg = errMsg + "You must be 15 or older to apply for this job\n";
result = false;
}
if (!(postcode.charAt(0) == 3 || postcode.charAt(0) == 8) && state == "VIC") {
errMsg = errMsg + "Your state and postcode do not match. State VIC postcodes must start with a 3 or 8\n";
result = false;
} else if (!(postcode.charAt(0) == 1 || postcode.charAt(0) == 2) && state == "NSW") {
errMsg = errMsg + "Your state and postcode do not match. State NSW postcodes must start with a 1 or 2\n";
result = false;
} else if (!(postcode.charAt(0) == 4 || postcode.charAt(0) == 9) && state == "QLD") {
errMsg = errMsg + "Your state and postcode do not match. State QLD postcodes must start with a 4 or 9\n";
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "NT") {
errMsg = errMsg + "Your state and postcode do not match. State NT postcodes must start with a 0\n";
result = false;
} else if (!(postcode.charAt(0) == 6) && state == "WA") {
errMsg = errMsg + "Your state and postcode do not match. State WA postcodes must start with a 6\n";
result = false;
} else if (!(postcode.charAt(0) == 5) && state == "SA") {
errMsg = errMsg + "Your state and postcode do not match. State SA postcodes must start with a 5\n";
result = false;
} else if (!(postcode.charAt(0) == 7) && state == "TAS") {
errMsg = errMsg + "Your state and postcode do not match. State TAS postcodes must start with a 7\n";
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "ACT") {
errMsg = errMsg + "Your state and postcode do not match. State ACT postcodes must start with a 0\n";
result = false;
} else {
result = true;
}
if (other && document.getElementById("otherText").value.trim().length === 0) {
errMsg = errMsg + "You have selected other skills, you must enter one other skill in the text box\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
//document.getElementById("errors").innerHTML = errMsg;
}
if (result == true) {
storeForm(firstName, familyName, midName, dob, male, female, street, suburb, state, postcode, email, number, XML, Java, Python, SQL, PERL, MySQL, Windows, UNIX, Linux, other, otherText)
}
return result; //if false the information will not be sent to the server
}
function storeForm(firstName, familyName, midName, dob, male, female, street, suburb, state, postcode, email, number, XML, Java, Python, SQL, PERL, MySQL, Windows, UNIX, Linux, other, otherText) {
//get values and assign them to sessionStorage attribute.
//we use the same name for the attrubute and the element id to avoid confustion
sessionStorage.firstName = firstName;
sessionStorage.familyName = familyName;
sessionStorage.midName = midName;
sessionStorage.dob = dob;
sessionStorage.male = male;
sessionStorage.female = female;
sessionStorage.street = street;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = postcode;
sessionStorage.email = email;
sessionStorage.number = number;
sessionStorage.XML = XML;
sessionStorage.Java = Java;
sessionStorage.Python = Python;
sessionStorage.SQL = SQL;
sessionStorage.PERL = PERL;
sessionStorage.MySQL = MySQL;
sessionStorage.Windows = Windows;
sessionStorage.UNIX = UNIX;
sessionStorage.Linux = Linux;
sessionStorage.other = other;
sessionStorage.otherText = otherText;
}
/* check if session day on user exists and if so prefill the form*/
function prefillForm() {
if (sessionStorage.firstName != undefined) {
document.getElementById("firstName").value = sessionStorage.firstName;
document.getElementById("familyName").value = sessionStorage.familyName;
document.getElementById("midName").value = sessionStorage.midName;
document.getElementById("dob").value = sessionStorage.dob;
if (sessionStorage.male == ("true")) {
document.getElementById("male").checked = true;
}
if (sessionStorage.female == ("true")) {
document.getElementById("female").checked = true;
}
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("number").value = sessionStorage.number;
if (sessionStorage.XML == ("true")) {
document.getElementById("XML").checked = true;
}
if (sessionStorage.Java == ("true")) {
document.getElementById("Java").checked = true;
}
if (sessionStorage.Python == ("true")) {
document.getElementById("Python").checked = true;
}
if (sessionStorage.SQL == ("true")) {
document.getElementById("SQL").checked = true;
}
if (sessionStorage.PERL == ("true")) {
document.getElementById("PERL").checked = true;
}
if (sessionStorage.MySQL == ("true")) {
document.getElementById("MySQL").checked = true;
}
if (sessionStorage.Windows == ("true")) {
document.getElementById("Windows").checked = true;
}
if (sessionStorage.UNIX == ("true")) {
document.getElementById("UNIX").checked = true;
}
if (sessionStorage.Linux == ("true")) {
document.getElementById("Linux").checked = true;
}
if (sessionStorage.other == ("true")) {
document.getElementById("other").checked = sessionStorage.other;
}
document.getElementById("otherText").value = sessionStorage.otherText;
}
}
function referenceNum1() {
//this function defines the local storage for the first job
localStorage.JobID = "QM593";
}
function referenceNum2() {
//this function defines the local storage for the second job;
localStorage.JobID = "CS197";
}
function init() {
var path = window.location.pathname;
var page = path.split("/").pop();
if (page == "apply.html") {
var regForm = document.getElementById("regform"); // get ref to the HTML element
window.onload = prefillForm();
regForm.onsubmit = validate; //register the event listener
//this puts the job id into the field
document.getElementById("JobID").value = localStorage.JobID;
} else {
//this makes it so that the 2 different functions run when the hyperlinks are clicked
var job1 = document.getElementById("job1");
var job2 = document.getElementById("job2");
var JobID
job1.onclick = referenceNum1;
job2.onclick = referenceNum2;
}
}
window.onload = init;
<article>
<header>
<h1>The Virtual World</h1>
<nav>
<p class="menu">Home</p>
<p class="menu">Jobs</p>
<p class="menu">Apply</p>
<p class="menu">About</p>
<p class="menu">Enhancements</p>
</nav>
</header>
<section id="required">
<h5>All fields with * are required</h5>
</section>
<form id="regform" method="post" action="http://mercury.swin.edu.au/it000000/formtest.php">
<fieldset>
<legend>Job Application</legend>
<p><label for="JobID">*Job ID:</label>
<input type="text" name="JobID" id="JobID" maxlength="5" size="10" pattern="^[a-zA-Z]{2}[0-9]{3}$" required="required" /></p>
<section id="choose">
<h5>Please choose from QM593 or CS197</h5>
</section>
<fieldset>
<legend>Personal Details</legend>
<p><label for="title">*Title:</label>
<select name="title" id="title" required="required">
<option value="">Please Select</option>
<option value="title">Dr</option>
<option value="title">Mr</option>
<option value="title">Miss</option>
<option value="title">Mrs</option>
<option value="title">Ms</option>
</select></p>
<p><label for="firstName">*First Name:</label>
<input type="text" name="firstName" id="firstName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" required="required" />
<label for="familyName">*Family Name:</label>
<input type="text" name="familyName" id="familyName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" required="required" /></p>
<p><label for="midName">Middle Name:</label>
<input type="text" name="midName" id="midName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" /></p>
<p><label for="dob">*Date of Birth:</label>
<input type="text" name="dob" id="dob" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" maxlength="10" size="10" required="required" /></p>
<p>*Gender:
<label for="male">Male</label>
<input type="radio" id="male" name="sex" value="male" required="required" />
<label for="female">Female</label>
<input type="radio" id="female" name="sex" value="female" required="required" /></p>
<p><label for="street">*Street Address:</label>
<input type="text" name="street" id="street" maxlength="40" size="30" required="required" /></p>
<p><label for="suburb">*Suburb/town:</label>
<input type="text" name="suburb" id="suburb" maxlength="40" size="20" required="required" /></p>
<p><label for="state">*State:</label>
<select name="state" id="state" required="required">
<option value="">Please Select</option>
<option value="state">VIC</option>
<option value="state">NSW</option>
<option value="state">QLD</option>
<option value="state">NT</option>
<option value="state">WA</option>
<option value="state">SA</option>
<option value="state">TAS</option>
<option value="state">ACT</option>
</select></p>
<p><label for="postcode">*Postcode:</label>
<input type="text" name="postcode" id="postcode" minlength="4" maxlength="4" size="10" pattern="^[0-9]{4}$" required="required" /></p>
<p><label for="email">*Email:</label>
<input type="email" name="email" id="email" size="30" required="required" /></p>
<p><label for="number">*Phone number:</label>
<input type="tel" name="number" id="number" minlength="8" maxlength="12" size="10" required="required" /></p>
<p>Skill list:</p>
<p><label for="C/C+">C/C+</label>
<input type="checkbox" id="C/C+" name="category[]" checked="checked" /></p>
<p><label for="XML">XML</label>
<input type="checkbox" id="XML" name="category[]" /></p>
<p><label for="Java">Java</label>
<input type="checkbox" id="Java" name="category[]" /></p>
<p><label for="Python">Python</label>
<input type="checkbox" id="Python" name="category[]" /></p>
<p><label for="SQL">SQL</label>
<input type="checkbox" id="SQL" name="category[]" /></p>
<p><label for="PERL">PERL</label>
<input type="checkbox" id="PERL" name="category[]" /></p>
<p><label for="MySQL">MySQL</label>
<input type="checkbox" id="MySQL" name="category[]" /></p>
<p><label for="Windows">Windows</label>
<input type="checkbox" id="Windows" name="category[]" /></p>
<p><label for="UNIX">UNIX</label>
<input type="checkbox" id="UNIX" name="category[]" /></p>
<p><label for="Linux">Linux</label>
<input type="checkbox" id="Linux" name="category[]" /></p>
<p><label for="other">Other Skills:</label>
<input type="checkbox" id="other" name="category[]" /></p>
<textarea id="otherText" name="other" rows="8" cols="70" placeholder="Please write any other skills you may have here..."></textarea>
</p>
</fieldset>
</fieldset>
<input type="submit" value="Apply" />
<input type="reset" value="Reset Application" />
</form>
</article>
you may create a generic function like that :
function show_error(element, message) {
element.parentElement.innerHTML += "<span class='error'>" + message + "</span>";
}
//call the function
show_error(document.getElementById('street'), 'error message');
.error {
color: red;
}
<p><label for="street">*Street Address:</label>
<input type="text" name="street" id="street" maxlength="40" size="30" required="required" /></p>
<p><label for="suburb">*Suburb/town:</label>
<input type="text" name="suburb" id="suburb" maxlength="40" size="20" required="required" /></p>
Then you can add another function to remove this error.
You can do the below to update when there is an error. I have added a small code to demonstrate.
$(document).ready(function() {
$("#btn").click(function() {
validate();
});
});
function validate() {
var errMsg = "";
var date = new Date($('#dpDoB').val());
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
if (age >= 80) { // Outside age ranges.
errMsg = errMsg + "You must be 80 or younger to apply for this job\n";
$("#dob").append("<span>" + errMsg + "</span>");
result = false;
}
if (age <= 15) { // Outside age ranges.
errMsg = errMsg + "You must be 15 or older to apply for this job\n";
$("#dob").append("<span>" + errMsg + "</span>");
result = false;
}
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<div id="form">
<div id="dob">
<input id="dpDoB" type="date" />
</div>
<div>
<input type="button" id="btn" class="btn btn-default" value="click me">
</div>
</div>
So what I am trying to do here is when the submit button is clicked pull all of the values from the textboxes and display them in a p tag that I have on my html page. I have been tring to figure this out for days. Can somebody let me know what I am doing wrong?
/* JavaScript */
$("#submit").click(function(){
var doc = $("#doctorate").val()
var Name = $("#first_name").val();
var Last = $("#last_name").val();
var T = Doc + " "+ Name + " " + Last
break
var Certs = $("#certs").val()
break
var Title = $("#title").val()
break
var Department = $("#department").val()
break
var Numb = $("#number").val()
break
var Web = $("#website").val()
break
var Ema = $("#email").val()
document.getElementById('output').innerHTML = T;
})
HTML unchanged
The big problem I see is that you keep assigning the same thing to your output. Try something like this (reduced for brevity):
function myOut() {
var output = document.getElementById("certs").value;
output = output + document.getElementById("title").value;
if (certs != null) {
document.getElementById("output").innerHTML = output;
}
}
<input type="text" id="certs" />
<input type="text" id="title" />
<p id="output"></p>
<button onclick="myOut()">
Sub
</button>
Here you can try this one.
var role = document.getElementById("role").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var doctorate = document.getElementById("doctorate").value;
var certs = document.getElementById("certs").value;
var title = document.getElementById("title").value;
var department = document.getElementById("department").value;
var number = document.getElementById("number").value;
var website = document.getElementById("website").value;
var email = document.getElementById("email").value;
var output = document.getElementById("output").value;
$("#submit").click(function(){
var N = $("#first_name").val();
var L = $("#last_name").val();
var T = N + " " + L;
if (doctorate.checked) {
document.getElementById('output').innerHTML = T;
}
if (first_name != null) {
document.getElementById('output').innerHTML = T;
}
if (last_name != null) {
document.getElementById('output').innerHTML = T;
}
if (certs != null) {
document.getElementById('output').innerHTML = T;
}
if (title != null) {
document.getElementById('output').innerHTML = T;
}
if (department != null) {
document.getElementById('output').innerHTML = T;
}
if (number != null) {
document.getElementById('output').innerHTML = T;
}
if (website != null) {
document.getElementById('output').innerHTML = T;
}
if (email != null) {
document.getElementById('output').innerHTML = T;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset id="role">
<legend>My Role</legend>
<label for="faculty">
<input type="radio" name="role" id="faculty" value="faculty" />
Faculty
</label>
<label for="staff">
<input type="radio" name="role" id="staff" value="staff" />
Staff
</label>
</fieldset>
<fieldset id="userinformation">
<legend>User Information</legend>
<label for="doctorate">
Doctorate?
<input type ="checkbox" id="doctorate" value="" />
</label>
<label>
First Name:
<input type="text" name="name" id="first_name" required />
</label>
<label>
Last Name:
<input type="text" name="name" id="last_name" required />
</label>
<label>
Certifications:
<input type="text" name="cert" id="certs" />
</label>
<label>
Title:
<input type="text" name="title" id="title" required />
</label>
<label>
Department:
<select id="department" required>
<option disabled selected value>-Select a Department-</option>
<option>School of Information Technology</option>
<option>Mathematics</option>
<option>English</option>
<option>History</option>
<option>Natural Sciences</option>
<option>Psychology</option>
<option>School of Health Sciences</option>
</select>
</label>
<label>
Primary Phone #:
<input type="tel" name="number" id="number" placeholder="444-123-1234" pattern="^\d{3}-\d{3}-\d{4}$"/>
</label>
<label>
Email:
<input type="email" name="email" id="email" placeholder="JDoe#example.com" required />
<span id="err3"></span>
</label>
<label>
Website:
<input type="text" name="website" id="website" placeholder="http//:www.example" pattern="https?://.+" />
</label>
</fieldset>
<fieldset id = "results">
<p id="output"></p>
</fieldset>
<fieldset id="submit_button">
<input type="button" id="submit" value="submit" />
</fieldset>
Can someone help me make this alert look much nicer? Like Maybe split up Each text box on its own line? I can not figure out how to make this look a lot cleaner and not just all piled on one line.
To see alert hit Lien radio button and then hit next without filling textboxes
http://jsfiddle.net/t4Lgm0n2/9/
function validateForm(){
var QnoText = ['lien']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'lname';
var eD = "";
if (CkStatus && document.getElementById(ids).value == '') {
eD = eD+' lienholder name';
document.getElementById(ids).focus();
flag = false;
}
ids2 = QnoText[i]+'laddress';
if (CkStatus && document.getElementById(ids2).value == '') {
eD=eD+' lienholder address';
document.getElementById(ids2).focus();
flag = false;
}
ids3 = 'datepicker2';
if (CkStatus && document.getElementById(ids3).value == '') {
eD=eD+' lien date';
document.getElementById(ids3).focus();
flag = false;
}
if(eD!="") alert("Please enter "+eD);
}
return flag;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" value="Yes" name="lien" id="lien" required="yes" onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<script type="text/javascript">
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
$("#div1 > .clearfix input:text").val("");
}
}
</script>
<div id="div1" style="display:none">
<div class="clearfix">
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" validateat="onSubmit" validate="maxlength" id="lienlname" size="54" maxlength="120" message="Please enter lienholder name." value="">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" validateat="onSubmit" validate="maxlength" id="lienladdress" size="54" maxlength="120" message="Please enter lienholder address." value="">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2" mask="99/99/9999" value="">
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
<input type="submit" name="submit" value="Next" onclick="validateForm()">
You can use new line characters \n to make text more readable:
var eD = [];
if (CkStatus && document.getElementById(ids).value == '') {
eD.push('Please enter lienholder name');
document.getElementById(ids).focus();
flag = false;
}
// ...
if (eD.length) alert(eD.join('\n'));
As you can see I'm also pushing error messages into ed array, which makes it more convenient to concatenate resulting message using .join() method.
Demo: http://jsfiddle.net/t4Lgm0n2/11/