I am trying to follow a tutorial on dynamic Jquery form validation but am stuck and cannot find my error. Chrome console tells me uncaught reference error: $ is not defined ( first line of my js).
this code should be validating as I type. Does anyone see an syntax error?
JS
$(function() {
/***********************************************************************************************/
/* Define some regular expressions */
/***********************************************************************************************/
var expEmail = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/,
expLettersOnly = /^[a-zA-Z ]+$/,
expLettersNumbers = /^[a-zA-Z0-9]*$/;
/***********************************************************************************************/
/* Function that checks if a field has the correct minimum length */
/***********************************************************************************************/
function validateLength( fieldValue, minLength ) {
// We remove trailing and leading whitespace
return ( $.trim( fieldValue ).length > minLength );
}
/***********************************************************************************************/
/* Validate form on typing */
/***********************************************************************************************/
$( "#rsgform1" ).on( "keyup", "input.validate-locally", function() {
validateField( $(this) );
});
/***********************************************************************************************/
/* Function that validates a field */
/***********************************************************************************************/
function validateField( field ) {
var errorText = "",
error = false,
value = field.val(),
siblings = field.siblings( ".demo-errors" );
// Test for which field is sent
switch ( field.attr( "name" ) ) {
case "firstname":
if ( !validateLength( value, 2 ) ) {
error = true;
errorText += "The name is too short!<br />";
}
if ( !expLettersOnly.test( value ) ) {
error = true;
errorText += "The name can only contain letters and spaces!";
}
break;
case "lastname":
if ( !validateLength( value, 2 ) ) {
error = true;
errorText += "The username is too short!<br />";
}
if ( !expLettersNumbers.test( value ) ) {
error = true;
errorText += "The username can only contain alphanumeric characters!";
}
break;
case "genDer":
if ( value === "0" ) {
error = true;
errorText += "Please select a gender!";
}
break;
case "email":
if ( !expEmail.test( value ) ) {
error = true;
errorText += "The email address format is invalid!";
}
break;
}
// Display the error message below the field
siblings.html( errorText );
}
});
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RSG Contact Us</title>
</head>
<body>
<div id="contactuscall">
<form id="rsgform1" name="rsgform1" method="post" action="" novalidate>
<fieldset id="field1">
<legend id="legend1">Contact info:</legend>
<p>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g John Smith, must be between 3 and 25 characters, letters and space only</span>
<span class="demo-errors"></span>
</p>
<p>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g John Smith, must be between 3 and 25 characters, letters and space only</span>
<span class="demo-errors"></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" id="email" name="email" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g Jsmith#gmail.com</span>
<span class="demo-errors"></span>
</p>
<p>
<label for="cellphone">Phone:</label>
<input type="text" id="cellphone" name="cellphone" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g 1-444-555-6666</span>
<span class="demo-errors"></span>
</p>
</fieldset>
<fieldset id="field2">
<legend id="legend2">Doggie info:</legend>
<p>
<label for="dogname">Name:</label>
<input type="text" id="dogname" name="dogname" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g Sparky, must be between 3 and 25 characters, letters and space only</span>
<span class="demo-errors"></span>
</p>
<p>
<label for="Breed">Breed:</label>
<input type="text" id="Breed" name="Breed" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g Beagle, Poodle, must be between 3 and 25 characters, letters and space only</span>
<span class="demo-errors"></span>
</p>
<p>
<label for="genDer">Gender:</label>
<select name="genDer" maxlength="10" class="validate-locally">
<option value="">- Select a Value-</option>
<option value="Intact Male"> Intact Male </option>
<option value="Neutered Male"> Neutered Male </option>
<option value="Intact Female"> Intact Female </option>
<option value="Neutered Female"> Neutered Female </option>
</select>
<span class="demo-errors"></span>
</p>
</fieldset>
<fieldset id="field3">
<legend id="legend3">Services Required:</legend>
<input type="checkbox" name="reasoNwalk" value="walkSale" class="textfield"/>I'm looking for a Dog Walker!
<input type="checkbox" name="reasoNfood" value="RawSale" class="textfield"/>I'm looking to purchase Raw Food!<br />
<input type="checkbox" name="reasoNgroom" value="groomSale" class="textfield"/>I'm looking for a Dog Groomer!
<input type="checkbox" name="reasoNtraining" value="trainingSale" class="textfield" />I'm looking for a Dog Trainer!
<span class="error"></span>
</fieldset>
<fieldset id="field4">
<legend id="legend4">Questions & Comments</legend>
<textarea rows="7" cols="90" id="freecomments" name="freecomments"></textarea>
</fieldset>
<!--<input id="submit" type="submit" name="submit" value="submit">-->
<input id="submit" type="submit" name="submit" value="submit">
</form>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="validate.js"></script>
</body>
</html>
Your error ddenotes that you are not included jQuery library.
Put the jquery.js before your script tag
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/script.js">
//your code here
</script>
Related
If any of the form validations do not match, it is supposed to add one to a counter. At the end, if the counter is greater than zero, it is supposed to return false and not allow the form to submit.
I've written the code in Brackets. I've tried using both a hosted site and live preview to test the code, both of which result in the same issue. I've tried turning the function into a variable. I've tried different methods of taking the variables from the form. I've tried simply copying a different solution I found to this through google. Nothing seems to be working to get the validation to work as intended.
I apologize ahead of time for the wall of code.
JavaScript:
function checkAll(){
var userNameVerification = "0-9a-zA-Z"; //must include upper and lowercase so that user may use caps
var phoneNumberVerification = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; //taken from w3resoucre for the setup of phone number verification
var checker = 0;
var userName = document.regForm.userName.value;
var password = document.regForm.passwordvalue;
var passwordVerify = document.regForm.passwordVerify.value;
var firstName = document.regForm.firstName.value;
var lastName = document.regForm.lastName.value;
var email = document.regForm.email.value;
var phoneNumber = document.regForm.phoneNumber.value;
var signUpNewsletter = document.regForm.phoneNumber.value;
//check if username is empty
if(userName == ""){
document.getElementById('errorUserName').innerHTML = "Username cannot be empty.";
checker++;
}
//make sure username uses proper characters
if(!userName.match(userNameVerification)){
document.getElementById('errorUserName').innerHTLM = "Enter only numbers and letters.";
checker++;
}
//check if password is empty or is shorter than 8 characters
if(password == "" || password.lenth < 8) {
document.getElementById('errorPassword').innerHTML = "Password should be at least 8 characters long.";
checker++;
}
//make sure confirmation of password is not shorter than 8 and is not empty
if(passwordVerify == "" || passwordVerify.lenth < 8) {
document.getElementById('errorPasswordVerify').innerHTML = "Confirmation Password should be at least 8 characters long.";
checker++;
}
//passwords match
if(password != passwordVerify){
document.getElementById('errorPasswordVerify').innerHTML = "Passwords do not match.";
checker++;
}
//check if first name is empty
if(firstName == ""){
document.getElementById('errorFirstName').innerHTML = "First name cannot be empty.";
checker++;
}
//check if last name is empty
if(lastName == ""){
document.getElementById('errorLastName').innerHTML = "Last Name cannot be empty.";
checker++;
}
//check if email is empty
if(email == ""){
document.getElementById('errorEmail').innerHTML = "Email cannot be empty.";
checker++;
}
//check that # and . are present
if(email.indexOf("#",0) < 0 || email.indexOf(".",0) < 0){
document.getElementById('errorEmail').innerHTML = "Enter a valid email address.";
checker++;
}
//check if phone number is empty
if(phoneNumber == ""){
document.getElementById('errorPhoneNumber').innerHTML = "You must enter a phone number.";
checker++;
}
//make sure phone number is in proper format
if(!phoneNumber.match(phoneNumberVerification)){
document.getElementById('errorPhoneNumber').innerHTML = "Enter a valid phone number in (XXX)XXX-XXXX format.";
checker++;
}
//make sure one of the radio buttons are clicked
if((signUpNewsletter[0].checked == false) && (signUpNewsletter[1].checked == false)){
document.getElementById('errorSignUp').innerHTML = "Please select one of the options.";
checker++;
}
//see if checker is greater than 0; if so, return false
if(checker > 0){
return false;
}
}
HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Invitation Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script type="text/javascript" src="js/registration.js"></script>
</head>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">CapellaVolunteers<span class="dotcom">.org</span></a>
</div>
<nav>
<ul class="topnav">
<li>Home
</li>
<li>Invitation
</li>
<li>Volunteers
</li>
<li>Gallery
</li>
<li>Registration
</li>
</ul>
</nav>
</header>
<section id="pageForm">
<form name="regForm" action="confirmation.php" method="POST">
<label for="userName">Username:</label>
<input type="text" name="userName" placeholder="Enter your Username" />
<span id="errorUserName"></span><br>
<label for="Password">Password:
</label>
<input type="password" name="password" placeholder="Enter your Password" />
<span id="errorPassword"></span><br>
<label for="passwordVerify">Verify your Password:
</label>
<input type="password" name="passwordVerify" placeholder="Enter in your Password again" />
<span id="errorPasswordVerify"></span><br>
<label for="firstName">First Name:
</label>
<input type="text" name="firstName" placeholder="Enter your First Name" />
<span id="errorFirstName"></span><br>
<label for="lastName">Last Name:
</label>
<input type="text" name="lastName" placeholder="Enter your Last Name" />
<span id="errorLastName"></span><br>
<label for="email">Email:
</label>
<input type="text" name="email" placeholder="Enter your Email Address" />
<span id="errorEmail"></span><br>
<label for="phoneNumber">Phone Number
</label>
<input type="text" name="lastName" placeholder="Enter your Phone Number" />
<span id="errorPhoneNumber"></span><br>
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" value="Yes" checked> Yes
<input type="radio" name="signUpNewsletter" value="No"> No
<span id="errorSignUp"></span><br>
<input type="submit" value="Next step" onsubmit="return checkAll();">
</form>
</section>
<footer>This events site is for IT3515 tasks.
</footer>
</body>
</html>
I expect the form to not submit when the information is not validated (for example, I try submitting an empty form, which it should not allow me to do), but it actually submits the form no matter what information is inserted into the form.
Add your onsubmit call to form instead of button, it works. Don't know about your logic, but it works. Run this code!
function checkAll(){
var condition = false;
if(condition){
alert ('All ok');
return true;
}
alert('Something wrong');
return false;
}
<section id="pageForm">
<form name="regForm" action="confirmation.php" method="POST" onsubmit="return checkAll();">
<label for="userName">Username:</label>
<input type="text" name="userName" placeholder="Enter your Username" />
<span id="errorUserName"></span><br>
<label for="Password">Password:
</label>
<input type="password" name="password" placeholder="Enter your Password" />
<span id="errorPassword"></span><br>
<label for="passwordVerify">Verify your Password:
</label>
<input type="password" name="passwordVerify" placeholder="Enter in your Password again" />
<span id="errorPasswordVerify"></span><br>
<label for="firstName">First Name:
</label>
<input type="text" name="firstName" placeholder="Enter your First Name" />
<span id="errorFirstName"></span><br>
<label for="lastName">Last Name:
</label>
<input type="text" name="lastName" placeholder="Enter your Last Name" />
<span id="errorLastName"></span><br>
<label for="email">Email:
</label>
<input type="text" name="email" placeholder="Enter your Email Address" />
<span id="errorEmail"></span><br>
<label for="phoneNumber">Phone Number
</label>
<input type="text" name="lastName" placeholder="Enter your Phone Number" />
<span id="errorPhoneNumber"></span><br>
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" value="Yes" checked> Yes
<input type="radio" name="signUpNewsletter" value="No"> No
<span id="errorSignUp"></span><br>
<input type="submit" value="Next step" >
</form>
</section>
This question already has answers here:
What is the meaning of onsubmit="return false"? (JavaScript, jQuery)
(4 answers)
Closed 5 years ago.
I have this HTML project that validates an empty form. The error is being displayed on the side of the inputs but only flashes for a second. I just want the error of the messages to be displayed once
This is my HTML code with the necessary links:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript - JQuery </title>
<link rel="stylesheet" type="text/css" href="contactform.css">
</head>
<body>
<h1 id="pageheading">Zedland Health Authority</h1>
<h2 class="sectionheading">Contact Form</h2>
<form id="register">
<fieldset id="controls">
<div>
<label class="formlabel" for="fname">First Name: </label>
<input id="fname" type="text" size="30" placeholder="First name"
autofocus>
<p id="fname-error" class="error" style="display:none; color:red;">*
You must enter a first name.</p>
</div>
<div>
<label class="formlabel"for="lname">Last Name: </label>
<input id="lname" type="text" size="30">
<p id="lname-error" class="error" style="display:none; color:red;">*
You must enter a Last name.</p>
</div>
<div>
<label class="formlabel" for="title">Title: </label>
<select id="title">
<option value="Mr">Mr.</option>
<option value="Ms">Ms.</option>
<option value="Mrs">Mrs.</option>
<option value="Miss">Miss.</option>
<option value="Master">Master.</option>
</select>
</div>
<div>
<label class="formlabel" for="heathauthoritynumber"><span>
<img src="tooltip.png" id="qmark" alt="Hint"></span>
Health Authority Number:
</label>
<input id="healthauthoritynumber" type="text" size="10">
<p id="hn-error" class="error" style="display:none; color:red;">*You
must enter a Health Authority Number eg('ZHA345742)</p>
<div class="tooltip" id="ttip">If you do not know your ZHA number
,please contact your GP</div>
</div>
<div>
<label class="formlabel" for="email">Email: </label>
<input id="email" type="text" size="40">
<p id="email-error" class="error" style="display:none; color:red;">You
must enter email</p>
</div>
<div>
<label class="formlabel" for="telephone">Telephone Number: </label>
<input id="telephone" type="text" size="40">
<p id="tele-error" class="error" style="display:none; color:red;">You
must enter a telephone</p>
</div>
<div class="formlabel">
<input id="submit-button" type="submit" value="Submit" >
</div>
</fieldset>
</form>
<script src="contactform.js"></script>
</body>
</html>
This is my Javascript
function onSubmit(){
console.log("ive been submitted");
checkEmpty(document.getElementById('fname'),document.getElementById("fname-error"));
checkEmpty(document.getElementById('lname'),document.getElementById("lname-error"));
checkEmpty(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
checkEmpty(document.getElementById('email'),document.getElementById("email-error"));
checkEmpty(document.getElementById('telephone'),document.getElementById("tele-error"));
//checkValidHealthID(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
}
// Read about regular expressions using: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
// and http://stackoverflow.com/questions/25155970/validating-uk-phone-number-regex-c
function checkValidHealthID(inputID, errorID){
var re = new RegExp('/ZHA\d{6}$/');
if((inputID.value)!== re){
errorID.style.display = "inline";
}else
{
errorID.style.display = "none";
}
}
function checkEmpty(inputID, errorID){
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
console.log("checking empty");
if((inputID.value === "") || (inputID.value.length === 0)){
console.log("empty!!");
errorID.style.display = "inline";
}
else
{
errorID.style.display = "none";
}
}
function textHint(txtElem, defaultText) {
txtElem.value = defaultText;
txtElem.style.color = "#A8A8A8";
txtElem.style.fontStyle = "italic";
txtElem.onfocus = function() {
if (this.value === defaultText) {
this.value = "";
this.style.color = "#000";
this.style.fontStyle = "normal";
}
}
txtElem.onblur = function() {
if (this.value === "") {
this.value = defaultText;
this.style.color = "#A8A8A8";
this.style.fontStyle = "italic";
}
}
}
function textHints() {
//textHint(document.getElementById("firstName"), "Enter your first name");
textHint(document.getElementById('lname'), "Enter your last name");
textHint(document.getElementById('healthauthoritynumber'), "for eg
,ZHA346783");
textHint(document.getElementById('email'), "Enter your email");
textHint(document.getElementById('telephone'), "Enter your telephone
number");
}
function switchToolTip() {
document.getElementById('qmark').onmouseover = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='block';
}
document.getElementById('qmark').onmouseout = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='none';
}
}
//windows.onload=textHints();
//windows.onload=switchToolTip();
//window.onload=init;
document.getElementById("submit-button").onclick = onSubmit;
Your form is getting submitted which results in page reload. That's why you see the message flashing for a while. I saw the commented line in your JavaScript
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
You should get uncomment e.preventDefault().
Grab the click event as function onSubmit(event) and pass the event to checkEmpty.
my jquery is not connecting and I cannot figure out why. I've been stumped on this for hours and I cannot figure it out.
this is my html code. The file name is exercise6.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise 6</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JS/exercise6.js"> </script>
</head>
<body>
<form id="email_form" name="email_form" action="exercise6.html" method="get">
<fieldset class="info">
<legend>Contact Information</legend>
<p>
<input type="text" name="Lname" id="name2" value="" required />
<label for="name2"> Last</label>
</p>
<p>
<input type="text" name="mailAddie" id="mail1" value="" required />
<label for="mail1"> Address</label>
</p>
<p>
<input type="text" name="City" id="city1" value="" />
<label for="city1"> City</label>
</p>
<p>
<input type="text" name="State" id="state1" value="" />
<label for="state1"> State</label>
</p>
<p>
<input type="number" name="Zip" id="zip1" value="" />
<label for="zip1"> Zip</label>
</p>
<p>
<input type="number" name="phoneNum" id="number" />
<label for="number"> Phone</label>
</p>
</fieldset>
<fieldset>
<legend>Sign up for our email list</legend>
<p>
<label for="email_address1"> Email Address</label>
<input type="text" name="email_address1" id="email_address1" value="" />
<span>*</span><br>
</p>
<p>
<label for="email_address2"> Confirm Email Address</label>
<input type="text" name="email_address2" id="email_address2" value="" />
<span>*</span><br>
</p>
<p>
<label for="first_name"> First</label>
<input type="text" name="first_name" id="first_name" value="" />
<span>*</span><br>
</p>
</fieldset>
<p>
<label> </label>
<input type="submit" value="Join Our List" id="join_list" >
</p>
</form>
</body>
</html>
and this is my javascript. The file name is exercise6.js and it is located in a file named JS. I do not know what I am doing wrong.
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
)};
)};
Can anyone help me?
The last two lines of exercise6.js both have a syntax error.
Change:
)};
)};
To:
});
});
To find this yourself next time, try using web development IDE like NetBeans with the help of right click with mouse to inspect in browser debug console, which would have even shown you where is this kind of error.
Your js code has some errors for close the function "});" try this
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
});
});
I have a quiz with values that are added to a sum which determines the image displayed but is only showing me my raw .js file when I click submit. I am hosting it and am not sure why it is showing me this. The previous function in the file work, since the validation works and is found in that file.
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="author" content="Kenneth Dunn" />
<meta name="description" content="" />
<link rel="stylesheet" href="css/random.css" type="text/css" />
</head>
<body>
<div id="page">
<div id="logo">
<h1>Overwatch</h1>
</div>
<div id="content">
<h2 align="center">Overwatch Quiz</h2>
<p>
Hi there! This quiz is dedicated to one of my favorite games Overwatch!
</p>
<form action="js/random.js" method="post" name="quiz_form" onsubmit="owchar()">
<p>
<br>
<input id='fName' name "first_name" type="text" placeholder="First Name" onblur="this.placeholder='First Name'" onfocus="this.placeholder='Use only letters'" class="validate" />
<img width="45px" height="45px"src='img/Q.png' id="fNameImg" />
</p>
<p>
<br>
<input id="last_name" name="last_name" type="text" placeholder="Last Name" onblur="this.placeholder='Last Name'" onfocus="this.placeholder='Use only Letters'" class="validate"/>
<img width="45px" height="45px" src='img/Q.png' id="last_nameImg" />
</p>
<p>
<br>
<input id="email" name="email" type="email" placeholder="Email" onblur="this.placeholder='Email'" onfocus="this.placeholder='Must contain # '" class="validate" />
<img width="45px" height="45px" src='img/Q.png' id="emailImg" />
</p>
<p>
<br>
<input id='phone' name="number" type="tel" placeholder="Phone Number" onblur="this.placeholder='Phone Number'" onfocus="this.placeholder='Must follow xxx-xxx-xxx '" class="validate" />
<img width="45px" height="45px" src='img/Q.png' id="phoneImg" />
</p>
<p>
<br>
<input id='sulley' name="sulley" type="sulley" placeholder="Sulley Email" onblur="this.placeholder='Sulley Email Address'" onfocus="this.placeholder='Must contain ~ and https:// '" class="validate"/>
<img width="45px" height="45px" src='img/Q.png' id="sulleyImg" />
</p>
<br>
<br>
<p>
<h2>Find out which Overwatch character you are most like!</h2>
<p>If you could pick what form to take in a fictional universe with magic and cool science what would you want to be?</p>
<input type="radio" name="exist" value="1">Male(Human).
<br>
<input type="radio" name="exist" value="2">Female(Human).
<br>
<input type="radio" name="exist" value="3">An Animal or something crazy.
<p>What is your preferred weapon to take on bad guys and defend yourself?</p>
<input type="radio" name="weapon" value="1">Twin Shotguns for close range.
<br>
<input type="radio" name="weapon" value="2">Twin pistols medium range.
<br>
<input type="radio" name="weapon" value="3">An electro gun that schocks enemies into submission.
<p>Which motivations most align with your own?
<p>
<input type="radio" name="idea" value="1">To become more powerful and to defeat those who would oppose me.
<br>
<input type="radio" name="idea" value="2">To explore the world and discover the unknown.
<br>
<input type="radio" name="idea" value="3">To protect my friends and those I care about.
<p>What do you look like?</p>
<input type="radio" name="look" value="1">Dark and mysterious black-hooded figure ,very edgy, like people in the Matix.
<br>
<input type="radio" name="look" value="2">Short and spunky British airforce pilot who can travel back in time.
<br>
<input type="radio" name="look" value="3">I'm a large gorilla who likes to eat bananas and peanut butter and can sheild my friends from harm.
<br>
<br>
<input type="submit" value="Submit">
<input type="reset" name="reset" id="reset" value="Reset" />
</p>
</form>
<br>
<br>
<br>
<br>
<h2 align="center" >Congratulations you got...</h2>
<div id="character" align="center" height="499" width="281" >
<img src="" id="character"/>
<br>
<br>
<br>
</div>
<div id="footer">
<h2 align="center">Created by Kenneth Dunn </h2>
</p>
</div>
</div>
</div>
<script src="js/random.js" type="text/javascript"></script>
</body>
</html>
JS
function validateData() {
console.log(this);
var letters = /^[A-Za-z]+$/;
var email = [#];
var tel = /^\d{3}-\d{3}-\d{4}$/gm;
var sulley = /[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/;
var imgId = this.id + 'Img';
var img = document.getElementById(imgId);
console.log(img)
var valid = false;
if (this.type == 'text') {
if (this.value.match(letters)) {
valid = true;
}
}
if (this.type == 'email') {
if (this.value.match(email)) {
valid = true;
}
}
if (this.type == 'tel') {
if (this.value.match(tel)) {
valid = true;
}
}
if (this.type == 'sulley') {
if (this.value.match(sulley)) {
valid = true;
}
}
if (valid) {
img.src = "img/check.png";
} else {
img.src = "img/redx.png";
}
}
var els = document.getElementsByClassName("validate");
for(i=0 ; i<els.length ; i++){
els[i].addEventListener("change", validateData, false);
}
function owchar(){
var sum = 0;
var w = document.forms["quiz_form"]["exist"].value;
sum+=w;
var q = document.forms["quiz_form"]["weapon"].value;
sum+=q;
var r = document.forms["quiz_form"]["idea"].value;
sum+=r;
var g = document.forms["quiz_form"]["look"].value;
sum+=g;
if (sum>1 && sum<6){
document.getElementById("character").src="img/reaper.png";
return false;
}
else if (sum>6 && sum<9){
document.getElementById("character").src="img/tracer.jpeg";
return false;
}
else {
document.getElementById("character").src="img/winston.png";
return false;
}
}
Your form is defined as:
<form action="js/random.js" method="post" name="quiz_form" onsubmit="owchar()">
The action tells the browser where to go after submission, not what js file to look in. Javascript uses a shared global scope, meaning that all JS files use the same global scope, even ones built directly into the page. Because of this Javascript awesomeness -- or weirdness (depending on your views) -- you don't need to specify where the code is that you want to run, you just have to load the code (using a <script> tag).
TL;DR;
Change this line so that it looks like the following example:
<form name="quiz_form" onsubmit="owchar()">
I made an application for people to fill out an application. I did some of the in form validation but now I want to ensure that when the user hits the submit button it checks to ensure that all field are filled out. I am stuck and cannot figure out the last part of this puzzle.
I believe all I need to make this work is a Application.js If someone could take a look at this and let me know what if anything I am missing. I did not include the CSS sheet or photos. Thank you for taking the time to help.
Here is the form. "Application.html"
<!DOCTYPE html>
<html>
<head>
<center><h1>AIFC Application Form</h1></center>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<title>AIFC Application</title>
<meta charset="utf-8">
<meta name="author" content="Paul Skinner">
<link rel="stylesheet" type="text/css" href="Application.css" />
<style type="text/css">
</style>
<script src="Application.js"></script>
<script src="Application_Library.js"></script>
<script type="text/javascript">
function updateTotal() {
var basePrice = 50;
var optionsPrice = 0;
var memberPrice = 0;
function checkPayment() {
if (document.getElementById('payment0').checked) {
optionsPrice += 1;
}
if (document.getElementById('payment1').checked) {
optionsPrice += 9.6;
}
} // end of checking for payment
function checkJumper() {
if (document.getElementById('jumper0').checked) {
optionsPrice += 0;
}
if (document.getElementById('jumper1').checked) {
optionsPrice += 4.4;
}
} // end of checking for Jumper
function checkMembership() {
if (document.getElementById('membership').value == 'Basic') {
memberPrice += 75;
}
if (document.getElementById('membership').value == 'Silver') {
memberPrice += 125;
}
if (document.getElementById('membership').value == 'Gold') {
memberPrice += 150;
}
} // end of check membership function
checkPayment();
checkJumper();
checkMembership();
var totalPrice = basePrice + (optionsPrice * memberPrice);
document.getElementById('optionsPrice').innerHTML = optionsPrice;
document.getElementById('memberPrice').innerHTML = "$ " + memberPrice;
document.getElementById('totalPrice').innerHTML = "$ " + totalPrice;
}
</script>
</head>
<body>
<div id="top">
<nav class="horizontalNav">
<ul>
<li>Home</li>
<li>Application</li>
<li>Who We Are</li>
<li>Our Packages</li>
</ul>
</nav></div>
<section>
<table>
<tr style="white-space:nowrap; clear:both">
<td><img src="Images/girl punching.jpg" alt="Girl Punching" style=" float:left; height:200px" /></td>
<td><img src="images/fitness.jpg" alt="Weights" style=" float:right; height:200px; width:900px" /></td>
</tr>
</table>
</section>
<form action="#" method="get" name="application" id="application" >
<div id="form">
<fieldset>
<legend>Payment Type</legend><br>
<input type="radio" name="payment" id="payment0" value="payment0" onchange="updateTotal()"> Monthly membership <br>
<input type="radio" name="payment" id="payment1" value="payment1" onchange="updateTotal()"> Yearly membership <b>Big Savings!</b> <br><br>
</fieldset>
<fieldset>
<legend>Choose a Location</legend><br>
<input type="radio" name="jumper" id="jumper0" value="jumper0" onchange="updateTotal()"> Single Gym location
<input type="radio" name="jumper" id="jumper1" value="jumper1" onchange="updateTotal()"> All Locations <br><br>
</fieldset>
<fieldset>
<legend>Membership Type</legend><br>
<select name="membership" id="membership" onchange="updateTotal()">
<option value="Basic">Basic Membership ($75)</option>
<option value="Silver">Silver Membership ($125)</option>
<option value="Gold">Gold Membership ($150)</option><br>
</select>
</fieldset>
<fieldset>
<legend>Sex</legend><br>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
</fieldset>
</div>
<div id="prices">
<table>
<tr><td>Membership Application Fee</td><td id="basePrice">$50</td></tr>
<tr><td>Option factor</td><td id="optionsPrice"></td></tr>
<tr><td>Membership</td><td id="memberPrice"></td></tr>
<tr><td>Total</td><td id="totalPrice"></td></tr>
</table>
</div>
<div id="info">
<fieldset>
<legend>Personal Information</legend>
<label for="first_name">First Name:</label>
<input type="text" id="firstname" name="first" required autofocus title="First Name" placeholder="First Name" />
<span id="first_name_error"> </span><br>
<label for="last_name">Last Name:</label>
<input type="text" id="lastname" name="last" required title="Last Name" placeholder="Last Name"/>
<span id="last_name_error"> </span><br>
<label for="address">Address:</label>
<input type="text" id="address" name="address" required title="Address" placeholder="Address"/>
<span id="address_error"> </span><br>
<label for="city">City:</label>
<input type="text" id="city" name="city" required title="City" placeholder="City"/>
<span id="city_error"> </span><br>
<label for="state">State:</label>
<input type="text" id="state" maxlength="2" name="State" required title="State" placeholder="State"/>
<span id="state_error"> </span><br>
<label for="zip_code">Zip Code:</label>
<input type="text" id="zip" name="zip" required title="Zip Code" placeholder="Zip Code" pattern="\d{5}([\-]\d{4})?"/>
<span id="zip_error"> </span><br>
<label for="phone_number">Phone Number:</label>
<input type="text" id="phone" name="phone" required title="Optional Phone Number 999-999-9999" placeholder="999-999-9999" pattern="\d{3}[\-]\d{3}[\-]\d{4}"/>
<span id="phone_error"> </span><br>
<label for="date_of_birth">Date of Birth:</label>
<input type="date" name="date" required title="MM-DD-YYYY"/>
<span id="date_error"> </span><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required title="Email" placeholder="Email Address"/>
<span id="email_error"> </span>
<br>
</fieldset>
<br><br><center><input type="submit" id="submit" value="Become a Member"></center>
<br><center><input type="Reset" id="btn1" value="Reset Form"></center>
</div>
<br><br><div class="footer">
<address><center>
<b>American InterContinental Fitness Center</b> ☀
1578 Perseverance Lane ☀
Simple City, IL 60001
<br/> (630)432-1425
</address></center>
<br>
</div>
</form>
</body>
</html>
The next is the js: "Application_Library.js"
var $ = function (id) { return document.getElementById(id); }
var application = function () {
// All the different fields
this.field = [];
this.field["first_name"] = {};
this.field["last_name"] = {};
this.field["address"] = {};
this.field["city"] = {};
this.field["state"] = {};
this.field["zip"] = {};
this.field["phone"] = {};
this.field["date"] = {};
this.field["email"] = {};
// Field messages
this.field["state"].message = "Please use only a two letter State abbreviation.";
this.field["zip"].message = "Please use a 5 or 9 digit Zip Code";
this.field["phone"].message = "Please use 123-456-7890 format.";
this.field["email"].message = "Must be a vaild email address.";
// Error messages
this.field["email"].required = "Email is required";
this.field["confirmemail"].required = "Please confirm your email!";
this.field["confirmemail"].noMatch = "Emails do not Match!", "email";
this.field["first_name"].required = "First names are required.";
this.field["last_name"].required = "Last names are required.";
this.field["address"].required = "An Address is required";
this.field["city"].required = "A City is required";
this.field["state"].required = "A State is required";
this.field["state"].isState = "State invalid";
this.field["zip"].required = "A Zip code is required.";
this.field["zip"].isZip = "Zip code is invalid";
this.field["phone"].required = "A phone number is required";
this.field["phone"].isPhone = "The phone number is invalid";
this.field["date"].required = "Your date of birth is required";
}
Instead of writing your own javascript validation you can use the jQuery "form Validation Plug-in", which is an excellent tool for web pages to validate data entries at the client side using JavaScript. It's very simple to use.
Here is a sample tutorial
http://www.codeproject.com/Articles/213138/An-Example-to-Use-jQuery-Validation-Plugin
You should implement server side validation also for best security.
You can't just check data on JavaScript, you should also check it on server-side, because the client side is more accessible and user can change the JavaScript or even disable it, so the data would be invalidated.
You should write server-side validation too.
You forgot to show the Application.js file.
Also you can use HTML5 validation, without using any JavaScript:
http://www.sitepoint.com/html5-form-validation/