validation on states with postcode and checkbox list text area - javascript

So far my java script only consist of the age validation but I need to have more which is when the user selects a state the first digit of the postcode should be as such VIC = 3 OR 8, NSW = 1 OR 2 ,QLD = 4 OR 9 ,NT = 0 ,WA = 6 ,SA=5 ,TAS=7 ,ACT= 0. Another one is when a user selects "Other skill" in the checkbox list they have to write in it so it cannot be blank. How do I go about doing these validations without using any library code?
"use strict";
/*get variables from form and check rules*/
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var age = document.getElementById("age").value;
var state = document.getElementById("state").value;
var postcode = document.getElementById("postcode").value;
//get varibles from form and check rules here
// if something is wrong set result = false, and concatenate error message
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
if (age <= 15 && age >= 80) { // Outside age ranges.
errMsg = errMsg + "You must be between the ages of 15 to 80 to apply for this job\n"
result = false;
}
/** if (/^[3][0-9]{3}$/) for postcode*/
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
}
return result; //if false the information will not be sent to the server
}
function init() {
var regForm = document.getElementById("regForm"); // get ref to the HTML element
regForm.onsubmit = validate; //register the event listener
}
window.onload = init;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="Prototype Website" />
<meta name="keywords" content="HTML, CSS, JavaScript" />
<title>The Virtual World</title>
<link href="styles/style.css" rel="stylesheet" />
<script src="apply.js"></script>
</head>
<body>
<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> </p>
<p>
<textarea id="other" 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>
</body>
</html>

Try something using match jquery like below.
"use strict";
/*get variables from form and check rules*/
function validate() {
var errMsg = "";
/* stores the error message */
if($('#state').find(':selected').text() === 'VIC' && $('#postcode').val().match('^3')){
//do your codings
}
else{
alert(errMsg);
}
}
function init() {
var regForm = document.getElementById("regForm"); // get ref to the HTML element
regForm.onsubmit = validate; //register the event listener
}
window.onload = init;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<body>
<article>
<header>
<h1>The Virtual World</h1>
</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>Personal Details</legend>
<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 /></p>
</fieldset>
<input type="submit" value="Apply" />
<input type="reset" value="Reset Application" />
</form>
</article>
</body>
</html>

Use regex to validate post code.
Try these two functions to validate postcode and skills
HTML - add new checkbox to Other. I've only added testing fields to the form.
function validate() {
if(!validateOtherSkills() || validatePostCode()){
result = false;
}
return result; //if false the information will not be sent to the server
}
function validateOtherSkills(){
var state = document.getElementById("OtherSK").checked;
if(state && document.getElementById("other").value.trim().length===0){
alert('Specify other skills');
return false;
}
return true;
}
function validatePostCode(){
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").options[document.getElementById("state").selectedIndex].text;
var regex;
//VIC = 3 OR 8, NSW = 1 OR 2 ,QLD = 4 OR 9 ,NT = 0 ,WA = 6 ,SA=5 ,TAS=7 ,ACT= 0.
switch (state) {
case "Please Select":
return false;
case "VIC":
regex = new RegExp(/(3|8)\d+/);
break;
case "NSW":
regex = new RegExp(/(1|2)\d+/);
break;
case "QLD":
regex = new RegExp(/(4|9)\d+/);
break;
case "NT":
regex = new RegExp(/0\d+/);
break;
case "WA":
regex = new RegExp(/6\d+/);
break;
case "SA":
regex = new RegExp(/5\d+/);
break;
case "TAS":
regex = new RegExp(/7\d+/);
break;
case "ACT":
regex = new RegExp(/0\d+/);
break;
}
var result = postcode.match(regex);
if(!result){
alert('Postal code invalid');
}
return result;
}
function init() {
var regForm = document.getElementById("regForm"); // get ref to the HTML element
regForm.onsubmit = validate; //register the event listener
}
window.onload = init;
<article>
<section id="required">
<h5>All fields with * are required</h5>
</section>
<form id="regForm" method="post" action="">
<fieldset>
<legend>Job Application</legend>
<section id="choose">
<h5>Please choose from QM593 or CS197</h5>
</section>
<fieldset>
<legend>Personal Details</legend>
<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>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="OtherSK">Other</label>
<input type="checkbox" id="OtherSK" name="category[]" /></p>
<p><label for="other">Other Skills:</label> </p>
<p>
<textarea id="other" 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>

Related

Why aren't my placeholders working with an auto-fill script?

function getBooking() {
if (sessionStorage.fname != undefined) {
document.getElementById("confirm_fname").textContent = sessionStorage.fname;
document.getElementById("confirm_lname").textContent = sessionStorage.lname;
document.getElementById("confirm_email").textContent = sessionStorage.email;
document.getElementById("confirm_gender").textContent = sessionStorage.gender;
document.getElementById("confirm_phone").textContent = sessionStorage.phone;
document.getElementById("confirm_start").textContent = sessionStorage.start;
document.getElementById("confirm_streetname").textContent = sessionStorage.streetname;
document.getElementById("confirm_suburb").textContent = sessionStorage.suburb;
document.getElementById("confirm_state").textContent = sessionStorage.state;
document.getElementById("confirm_postcode").textContent = sessionStorage.postcode;
document.getElementById("confirm_skill").textContent = sessionStorage.skill;
document.getElementById("confirm_other").textContent = sessionStorage.other;
document.getElementById("confirm_otherbox").textContent = sessionStorage.otherbox;
document.getElementById("a_fname").value = sessionStorage.fname;
document.getElementById("a_lname").value = sessionStorage.lname;
document.getElementById("a_email").value = sessionStorage.email;
document.getElementById("a_gender").value = sessionStorage.gender;
document.getElementById("a_phone").value = sessionStorage.phone;
document.getElementById("a_start").value = sessionStorage.start;
document.getElementById("a_streetname").value = sessionStorage.streetname;
document.getElementById("a_suburb").value = sessionStorage.suburb;
document.getElementById("a_state").value = sessionStorage.state;
document.getElementById("a_postcode").value = sessionStorage.postcode;
document.getElementById("a_skill").value = sessionStorage.skill;
document.getElementById("a_other").value = sessionStorage.other;
document.getElementById("a_otherbox").value = sessionStorage.otherbox;
}
}
function prefillcard()
{
document.getElementById("fname").value = sessionStorage.fname;
document.getElementById("lname").value = sessionStorage.lname;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("gender").value = sessionStorage.gender;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("start").value = sessionStorage.start;
document.getElementById("streetname").value = sessionStorage.streetname;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("skill").value = sessionStorage.skill;
document.getElementById("other").value = sessionStorage.other;
document.getElementById("otherbox").value = sessionStorage.otherbox;
}
window.addEventListener("DOMContentLoaded", prefillcard);
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
<section class="applything">
<h2> Warning: you have 3 minutes to fill out the form before being redirected back to previous page </h2>
<br>
<h2>Job application:</h2>
<br>
<div class="containerr">
<body>
<form action="https://mercury.swin.edu.au/it000000/formtest.php" method="post" id="regform">
<p>Job Reference Number: <span id="job1"></span> <span id="job2"></span> <span id="job3"></span>
</p>
<br>
<br>
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name.." required="required" maxlength="25" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name.." required="required" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="start">Date of birth:</label>
<input type="date" id="start" required="required" name="date of birth" value="2021-10-04" />
<br>
<br>
<label for="gender"> Select your gender</label>
<br>
<br>
<select name="gender" id="gender" required="required">
<option value="" selected>Please Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
<label for="streetname">Street Address</label>
<input type="text" id="streetname" name="streetname" required="required" placeholder="Your street name..." maxlength="40" />
<label for="suburb">Suburb/Town</label>
<input type="text" id="suburb" name="suburb" required="required" placeholder="Your suburb/town..." maxlength="40">
<label for="state">Choose a state:</label>
<br>
<select name="state" id="state" required="required">
<option value="">Please Select</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="ACT">ACT</option>
</select>
<br>
<br>
<label for="postcode">Postcode</label>
<input type="text" id="postcode" name="postcode" required="required" placeholder="Your postcode..." maxlength="4" minlength="4" pattern="^[0-9]{4}$">
<label for="email">Email Address</label>
<input type="text" id="email" name="emailadd" placeholder="Your email address.." required="required">
<label for="phone">Phone Number</label>
<input type="text" id="phone" name="phonenumb" placeholder="e.g. 0451124561" minlength="8" maxlength="12" required="required">
<br>
<label>Skills</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill1" value="Javascript">
<label for="skill1"> Extensive knowledge of Javascript</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill2" value="Python">
<label for="skill2"> Extensive knowledge of Python</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill3" value="Networking">
<label for="skill3"> Extensive knowledge of Networking</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill4" value="Data Storage">
<label for="skill4"> Extensive knowledge of Data storage fundamentals</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill5" value="Security Foundations">
<label for="skill5"> Extensive knowledge of Security foundations</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill6" value="AWS Service Selection">
<label for="skill6"> Extensive knowledge of AWS service selection</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill7" value="Teamwork">
<label for="skill7"> Ability to work in a team</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill8" value="5+ Years">
<label for="skill8"> 5+ years experience</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill9" value="10+ Years">
<label for="skill9"> 10+ years experience</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill10" value="20+ Years">
<label for="skill10"> 20+ years experience</label>
<br>
<br>
<input type="checkbox" id="other" name="other" value="other" onclick="otherCheckBox()" />
<label for="other"> I have other skills. Please list other skills below.</label>
<br>
<br>
<br>
<label for="subject">Subject:</label>
<textarea id="otherbox" name="other skill" placeholder="textarea" style="height:200px"></textarea>
<input type="submit" value="Apply">
<br>
<br>
<input type="reset" id="cancelpurchase" value="Cancel Application"></input>
</form>
<script type="text/javascript">
document.getElementById("job1").innerHTML = localStorage.getItem("jobreference1");
document.getElementById("job2").innerHTML = localStorage.getItem("jobreference2");
document.getElementById("job3").innerHTML = localStorage.getItem("jobreference3");
</script>
</body>
</div>
</section>
<div class="footer">
<div class="footer-content"></div>
<div class="footer-bottom"></div> © swintech.com | Designed by Bilal El-leissy
</div>
</body>
</html>
I've set up a function that auto-fills the form if the user had previously submitted it in the same browser session. The only problem is that, before submitting it for the first time, a text fills every input reading "undefined" despite me adding placeholders in HTML. How do I make it so that the "undefined" goes away?

Trying to set a radio button in HTML document using javascript with data from cookie

I have a question. I got this registration form that stores the values into a cookie based on an ID name. When you go back to the same registration form and fill in the ID name that was already saved in a cookie, it will pull the data from cookie and prefill the form.
I have the following code and it works on form fields, but not on radio buttons. Not sure what is going on with radio buttons
//This function fills in the form based on entered conference ID
function fillForm(name) {
var cookie = getCookie(name).toString();
var newCookie = decodeURIComponent(cookie);
var newArray = newCookie.split(";");
//For testing values to make sure they're there
alert(newArray);
document.getElementById("title").value = newArray[0];
document.getElementById("firstname").value = newArray[1];
document.getElementById("lastname").value = newArray[2];
document.getElementById("addressone").value = newArray[3];
document.getElementById("addresstwo").value = newArray[4];
document.getElementById("city").value = newArray[5];
document.getElementById("state").value = newArray[6];
document.getElementById("zipcode").value = newArray[7];
document.getElementById("tel").value = newArray[8];
document.getElementById("email").value = newArray[9];
document.getElementById("website").value = newArray[10];
document.getElementById("position").value = newArray[11];
document.getElementById("companyname").value = newArray[12];
if(newArray[13]) {
document.getElementById("mealone").checked = true;
}
else {
document.getElementById("mealtwo").checked = true;
}
if(newArray[15]) {
document.getElementById("sesonea").checked = true;
}
else if(newArray[16]) {
document.getElementById("sesoneb").checked = true;
}
else {
document.getElementById("sesonec").checked = true;
}
if(newArray[18]) {
document.getElementById("sestwoa").checked = true;
}
else if(newArray[19]) {
document.getElementById("sestwob").checked = true;
}
else {
document.getElementById("sestwoc").checked = true;
}
if(newArray[21]) {
document.getElementById("sesthreea").checked = true;
}
else if(newArray[22]) {
document.getElementById("sesthreeb").checked = true;
}
else {
document.getElementById("sesthreec").checked = true;
}
document.getElementById("billfirstname").value = newArray[24];
document.getElementById("billlastname").value = newArray[25];
if(newArray[26]) {
document.getElementById("carda").checked = true;
}
else if(newArray[27]) {
document.getElementById("cardb").checked = true;
}
else {
document.getElementById("cardc").checked = true;
}
document.getElementById("cardnumber").value = newArray[29];
document.getElementById("csv").value = newArray[30];
document.getElementById("cardexpmonth").value = newArray[31];
document.getElementById("cardexpyear").value = newArray[32];
}
It's driving me nuts. I setup an alert to make sure I can see all the data correctly in the array, but it's not selecting the correct radio buttons.
Edit: HTML form:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="js/jsdefault.js"></script>
<link rel="stylesheet" href="css/webdefault.css">
<meta charset="UTF-8">
<meta name="description" content="Conference Website">
<meta name="keywords" content="Conference, website">
<meta name="author" content="Rafal Dudek">
<meta name="robots" content="all">
<title>Conference Registration</title>
</head>
<body>
<div id="header">
<nav>
<ul>
<li>Index</li>
<li>Awards</li>
<li>Activities</li>
<li>Meals</li>
<li>Keynote</li>
<li>Workshop Schedule</li>
<li>Registration</li>
</ul>
</nav>
</div>
<div id="main">
<form action="thankyou.html" id="registration" onsubmit="return check()" method="get">
<fieldset>
<legend>Conference ID</legend>
<label>Conference ID: <input type="text" oninput="fillForm(this.value)" id="confID" name="confID" size="6" maxlength="6" required="required" pattern="[0-9]{6}" placeholder="123456" title="Enter a 6 digit conference ID number"></label><br />
</fieldset>
<fieldset>
<legend>Personal Information</legend>
<label for="title">Title:</label>
<select id="title">
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
<option value="Mrs.">Mrs.</option>
</select><br />
<label>First Name: <input type="text" id="firstname" name="firstname" size="30" maxlength="100" required="required" pattern="[a-zA-Z]+" placeholder="First Name" title="Enter your first name"></label><br />
<label>Last Name: <input type="text" id="lastname" name="lastname" size="30" maxlength="100" required="required" pattern="[a-zA-Z\-]+" placeholder="Last Name" title="Enter your last name"></label><br />
<label>Address 1: <input type="text" id="addressone" name="addressone" size="30" maxlength="100" required="required" pattern="[a-zA-Z0-9\ \#]+" placeholder="Address" title="Enter your address"></label><br />
<label>Address 2: <input type="text" id="addresstwo" name="addresstwo" size="30" maxlength="100" pattern="[a-zA-Z0-9\ \#]+" title="Optional: Enter part 2 of your address"></label><br />
<label>City: <input type="text" id="city" name="city" size="30" maxlength="100" required="required" pattern="[a-zA-Z\ ]+" placeholder="City" title="Enter your city"></label><br />
<label title="state">State:</label>
<select title="state" id="state">
<option value="AL">AL</option>
<option value="AK">AK</option>
<option value="AR">AR</option>
<option value="AZ">AZ</option>
<option value="CA">CA</option>
<option value="CO">CO</option>
<option value="CT">CT</option>
<option value="DC">DC</option>
<option value="DE">DE</option>
<option value="FL">FL</option>
<option value="GA">GA</option>
<option value="HI">HI</option>
<option value="IA">IA</option>
<option value="ID">ID</option>
<option value="IL">IL</option>
<option value="IN">IN</option>
<option value="KS">KS</option>
<option value="KY">KY</option>
<option value="LA">LA</option>
<option value="MA">MA</option>
<option value="MD">MD</option>
<option value="ME">ME</option>
<option value="MI">MI</option>
<option value="MN">MN</option>
<option value="MO">MO</option>
<option value="MS">MS</option>
<option value="MT">MT</option>
<option value="NC">NC</option>
<option value="NE">NE</option>
<option value="NH">NH</option>
<option value="NJ">NJ</option>
<option value="NM">NM</option>
<option value="NV">NV</option>
<option value="NY">NY</option>
<option value="ND">ND</option>
<option value="OH">OH</option>
<option value="OK">OK</option>
<option value="OR">OR</option>
<option value="PA">PA</option>
<option value="RI">RI</option>
<option value="SC">SC</option>
<option value="SD">SD</option>
<option value="TN">TN</option>
<option value="TX">TX</option>
<option value="UT">UT</option>
<option value="VT">VT</option>
<option value="VA">VA</option>
<option value="WA">WA</option>
<option value="WI">WI</option>
<option value="WV">WV</option>
<option value="WY">WY</option>
</select><br />
<label>Zip Code: <input type="text" id="zipcode" name="zipcode" size="10" maxlength="10" required="required" pattern="[0-9]{5}\-[0-9]{4}" placeholder="Zip Code" title="Enter zip code"></label><br />
<label>Telephone: <input type="text" id="tel" name="tel" size="30" maxlength="100" required="required" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" placeholder="Telephone" title="Enter telephone number"></label><br />
<label>Email: <input type="email" id="email" name="email" size="30" maxlength="100" required="required" pattern="([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Zaz]{2,4})" placeholder="example#example.com" title="Enter email address"></label><br />
</fieldset>
<fieldset>
<legend>Company Information</legend>
<label>Company Website: <input type="url" id="website" name="website" size="30" maxlength="100" placeholder="www.example.com" title="Enter website URL"></label><br />
<label>Position: <input type="text" id="position" name="position" size="30" maxlength="100" required="required" pattern="[a-zA-Z0-9\ \#]+" placeholder="Position" title="Enter your position"></label><br />
<label>Company Name: <input type="text" id="companyname" name="companyname" size="30" maxlength="100" required="required" pattern="[a-zA-Z0-9\ \#]+" placeholder="Company Name" title="Enter company name"></label><br />
</fieldset>
<fieldset>
<legend>Dining Information</legend>
<p>
Would you like a full meal or just day 2 dinner?<br />
<label><input type="radio" id="mealone" name="meal" value="full" required/> Full Meal ($250)</label>
<label><input type="radio" id="mealtwo" name="meal" value="part"/> Day 2 dinner only ($75)</label>
</p>
</fieldset>
<fieldset>
<legend>Workshop Information</legend>
<p>
Which workshops would you like to join?<br />
Outdoors Theme:
<label><input type="radio" id="sesonea" name="session_1" value="workshop_1" required /> Lawn Maintenance</label>
<label><input type="radio" id="sesoneb" name="session_1" value="workshop_2"/> Landscaping Ideas</label>
<label><input type="radio" id="sesonec" name="session_1" value="workshop_3" /> Pest Control</label><br />
Home Improvement Theme:
<label><input type="radio" id="sestwoa" name="session_2" value="workshop_4" /> Kitchen Remodeling</label>
<label><input type="radio" id="sestwob" name="session_2" value="workshop_5"/> Bathroom Remodeling</label>
<label><input type="radio" id="sestwoc" name="session_2" value="workshop_6" /> Home Improvement Ideas</label><br />
Repair Basics Theme:
<label><input type="radio" id="sesthreea" name="session_3" value="workshop_7" required/> General Appliance Troubleshooting</label>
<label><input type="radio" id="sesthreeb" name="session_3" value="workshop_8"/> Heat and A/C Unit Maintenance</label>
<label><input type="radio" id="sesthreec" name="session_3" value="workshop_9" /> Plumbing Basics</label><br />
</p>
</fieldset>
<fieldset>
<legend>Billing Information:</legend>
<label>Billing First Name: <input type="text" id="billfirstname" name="billfirstname" size="30" maxlength="100" required="required" pattern="[a-zA-Z]+" placeholder="First Name" title="Enter first name"></label><br />
<label>Billing Last Name: <input type="text" id="billlastname" name="billlastname" size="30" maxlength="100" required="required" pattern="[a-zA-Z\-]+" placeholder="Last Name" title="Enter last name"></label><br />
<p>
Card Type:<br />
<label><input type="radio" id="carda" name="card" value="visa" /> Visa</label>
<label><input type="radio" id="cardb" name="card" value="mastercard" required/> MasterCard</label>
<label><input type="radio" id="cardc" name="card" value="americanexpress"/> American Express</label>
</p>
<label>Card Number: <input type="text" id="cardnumber" name="cardnumber" size="16" maxlength="16" required="required" pattern="[0-9]{16}" placeholder="0000000000000000" title="Enter credit card number"></label><br />
<label>Card Security Value: <input type="text" id="csv" name="csv" size=4 maxlength="4" required="required" pattern="[0-9]{4}" placeholder="000" title="Enter CSV number"></label><br />
<label>Exp. Month (two digits): <input type="text" id="cardexpmonth" name="cardexpmonth" size="2" maxlength="2" required="required" pattern="(0[1-9]|1[0-2])" placeholder="MM" title="Enter two digit month"></label><br />
<label>Exp. Year (four digits): <input type="text" id="cardexpyear" name="cardexpyear" size="4" maxlength="4" required="required" pattern="[2][0]([1-2][6-9])" placeholder="YYYY" title="Enter four digit year"></label><br />
<input type="submit" value="Submit" />
</fieldset>
</form>
</div>
<div id="footer">
<address>
<small>
Contact Information:<br>
Peter John<br>
12345 Grape St.<br>
Thornton, CO 80233<br>
Telephone: 303-555-6666<br>
E-mail: peter.john#gmail.com
</small>
</address>
</div>
</body>
</html>
Adding get and set cookie functions too just in case:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
//This function gets cookie value based on conference ID
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Cookies are stored as Strings so when you do if(newArray[1]) you are saying if("false") or if("true") which in javascript
The result is false if the argument is the empty String (its length is zero); otherwise the result is true
source: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
and answer that gave source: https://stackoverflow.com/a/8693015/1309377
Any of your "false" are treated as true
to fix this you should be doing newArray[1] == "true"
//This function fills in the form based on entered conference ID
var newArray = ["true", "false", "true"] //newCookie.split(";");
if (newArray[0] == "true") {
document.getElementById("mealone").checked = true;
} else {
document.getElementById("mealtwo").checked = true;
}
if (newArray[1] == "true") {
document.getElementById("sesonea").checked = true;
} else if (newArray[2] == "true") {
document.getElementById("sesoneb").checked = true;
} else {
document.getElementById("sesonec").checked = true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="js/jsdefault.js"></script>
<link rel="stylesheet" href="css/webdefault.css">
<meta charset="UTF-8">
<meta name="description" content="Conference Website">
<meta name="keywords" content="Conference, website">
<meta name="author" content="Rafal Dudek">
<meta name="robots" content="all">
<title>Conference Registration</title>
</head>
<body>
<div id="main">
<form action="thankyou.html" id="registration" onsubmit="return check()" method="get">
<fieldset>
<legend>Dining Information</legend>
<p>
Would you like a full meal or just day 2 dinner?<br />
<label><input type="radio" id="mealone" name="meal" value="full" required/> Full Meal ($250)</label>
<label><input type="radio" id="mealtwo" name="meal" value="part"/> Day 2 dinner only ($75)</label>
</p>
</fieldset>
<fieldset>
<legend>Workshop Information</legend>
<p>
Which workshops would you like to join?<br /> Outdoors Theme:
<label><input type="radio" id="sesonea" name="session_1" value="workshop_1" required /> Lawn Maintenance</label>
<label><input type="radio" id="sesoneb" name="session_1" value="workshop_2"/> Landscaping Ideas</label>
<label><input type="radio" id="sesonec" name="session_1" value="workshop_3" /> Pest Control</label>
</p>
</fieldset>
</body>
</html>

validate dob with age verification

I am trying to make it so if someone is trying to fill in the form they must be between the ages of 15 to 80 but I am not sure how to use my date of birth to verify that the age is between 15 to 80. How would I go about doing this and how would I make sure the user that has entered their birthday is between the ages of 15 to 80?
"use strict";
/*get variables from form and check rules*/
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var age = document.getElementById("age").value;
var state = document.getElementById("state").value;
var postcode = document.getElementById("postcode").value;
//get varibles from form and check rules here
// if something is wrong set result = false, and concatenate error message
if (age <= 15) {
errMsg = errMsg + "You must be 15 or older to fill out this form\n"
result = false;
} else(age >= 80) {
errMsg = errMsg + "You must be 80 or younger to fill out this form\n"
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
}
return result; //if false the information will not be sent to the server
}
function init() {
var regForm = document.getElementById("regform"); // get ref to the HTML element
regForm.onsubmit = validate; //register the event listener
}
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> </p>
<p>
<textarea id="other" 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>
Since you know the date will be separated by '/' just do it the old fashion way of splitting the string into 3 and creating a date object.
var dob = document.getElementById("dob").value.split("/");
var date = new Date(dob[2], parseInt(dob[1]) - 1, dob[0]);
Then you can do your processing such as checking day, month, year to verify if they are between 15 and 80.
If you are not taking months and days into considerations then this simple if statement will fulfill the purpose.
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
if(age >= 15 && age <= 80){
// Between age ranges.
}
You can calculate the age from dob, and after do the same validation you have done .
dob = document.getElementById("dob").value;
dob = new Date(dob);
var today = new Date();
var age = Math.floor((today-dob) / (365.25 * 24 * 60 * 60 * 1000));
if (age <= 15) {
errMsg = errMsg + "You must be 15 or older to fill out this
form\n"
result = false;
} else (age >= 80) {
errMsg = errMsg + "You must be 80 or younger to fill out this
form\n"
result = false;
}
you can take in the string input of date, convert that to javascript's date object and subtract that from current time to check the age.
Code snippet:
var birthday = '1994-01-01';
var dateObj = new Date(birthday);
var diffTime = Date.now() - dateObj.getTime();
var diffAge = new Date(diffTime);
var age = diffAge.getFullYear() - 1970;
if(age < 15 || age > 80){
//do whatever here
console.log("age is not in the range");
}
You can reduce this to one line too:
(new Date(Date.now() - (new Date(birthday)).getTime())).getFullYear() - 1970;

Display html5 input value in a window alert and save the value in a .txt [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want two function first to display all the input value together in a window alert by clicking Display button and the second is to save this value in a .txt format by Clicking Submit with JavaScript Or PHP.
This is my Html code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="action_page.php">
ID:<br>
<input type="number" name="ID" id="ID">
<br>
Password:<br>
<input type="password" name="password" id="password">
<br>
First name:<br>
<input type="text" name="first name" id="first name">
<br>
last name:<br>
<input type="text" name="last name" id="last name">
<br>
Prmotion:<br>
<select name="promo" id="promo">
<option value="1">1 anne</option>
<option value="2">2 anne</option>
<option value="3">3 anne</option>
<option value="4">4 anne</option>
<option value="5">5 anne</option>
</select><br>
Date de Naissance:<br>
<input type="date" name="birthday" id="birthday">
<br>
Email:<br>
<input type="email" name="mail" id="mail">
<br>
Telephone:<br>
<input type="tel" name="telephone" id="telephone">
<br>
Sport Prefere:<br>
<input type="checkbox" name="sport" value="Natation"> Natation<br>
<input type="checkbox" name="sport" value="Soccer" checked> Soccer<br>
<input type="checkbox" name="sport" value="Tennis" checked> Tennis<br>
Sex:<br>
<input type="radio" name="sex" value="male" checked>Male
<br>
<input type="radio" name="sex" value="female">Female
<br>
Option:<br>
<select name="Option">
<option value="Telecom">Telecom</option>
<option value="Multi">multimedia</option>
<option value="Logi">Logiciel</option>
</select><br>
Comment:<br>
<textarea name="comment" id="comment"></textarea><br>
<input type="submit" value="Display">
<input type="submit" value="Submit">
</form>
</body>
</html>
You can use serializeArray method to create array of objects in form then display it in the alert.
To submit the form data you can use ajax.
Then in your php file action_page.php put the below code which will save the post values in a text file.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$myfile = fopen("hello.txt", "a") or die("Unable to open file!");
$txt = json_encode($_POST);
fwrite($myfile, $txt);
fclose($myfile);
}
$("#display").on("click", function() {
//alert($('form').serializeArray());
var fields = $('form').serializeArray();
var data = [];
jQuery.each(fields, function(i, field) {
data.push(field.value);
});
alert(data);
return false;
});
$("#submit").on("click", function() {
var fields = $('form').serialize();
var data = [];
$.ajax({
type: 'POST',
data: fields,
url: "action_page.php",
success: function(result) {
alert(result);
}
});
return false;
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="results"></div>
<form action="">
ID:
<br>
<input type="number" name="ID" id="ID">
<br>Password:
<br>
<input type="password" name="password" id="password">
<br>First name:
<br>
<input type="text" name="first name" id="first name">
<br>last name:
<br>
<input type="text" name="last name" id="last name">
<br>Prmotion:
<br>
<select name="promo" id="promo">
<option value="1">1 anne</option>
<option value="2">2 anne</option>
<option value="3">3 anne</option>
<option value="4">4 anne</option>
<option value="5">5 anne</option>
</select>
<br>Date de Naissance:
<br>
<input type="date" name="birthday" id="birthday">
<br>Email:
<br>
<input type="email" name="mail" id="mail">
<br>Telephone:
<br>
<input type="tel" name="telephone" id="telephone">
<br>Sport Prefere:
<br>
<input type="checkbox" name="sport" value="Natation">Natation
<br>
<input type="checkbox" name="sport" value="Soccer" checked>Soccer
<br>
<input type="checkbox" name="sport" value="Tennis" checked>Tennis
<br>Sex:
<br>
<input type="radio" name="sex" value="male" checked>Male
<br>
<input type="radio" name="sex" value="female">Female
<br>Option:
<br>
<select name="Option">
<option value="Telecom">Telecom</option>
<option value="Multi">multimedia</option>
<option value="Logi">Logiciel</option>
</select>
<br>Comment:
<br>
<textarea name="comment" id="comment"></textarea>
<br>
<input type="submit" id="display" value="Display">
<input type="submit" id="submit" value="Submit">
</form>
</body>
</html>

getElementsByName looping through all fields returning values using onChange event

I have a contact form. The contact form has inputs, selectors and radio buttons.
Question 1: Using the getElementsByName how do I get the index of a field using the onChange event? Would I use a For Loop?
Question 2: How do I do this with inputs that selectors and radio buttons?
Question 3: Once I get the data from an Index how do I use the index to the ID of the field as I then want to evaluate the data.
Thanks in advance!
Javascript
`// Var for element
var contactname = document.getElementsByName('cf')[1];
//Get value when clicking out of field
contactname.addEventListener('onchange',function(){
console.log(contactname.value);
});`
HTML Form
<!DOCTYPE html>
<html>
<head>
<title>Contact Me</title>
<link rel="stylesheet" type="text/css" href="contactform_Lab8.css">
</head>
<body>
<form id="contactus">
<fieldset>
<label for="name">Name:</label>
<input id="name" type="text" name="cf" autofocus required>
<label for="email">Email:</label>
<input id="email" type="email" name="cf" required>
<label for="phone">Phone:</label>
<input id="phone" type="tel" name="cf" required>
<label for="status">Status:
<select id="status" name="cf" required>
<option value="client">Client</option>
<option value="partner">Partner</option>
<option value="vendor">Vendor</option>
</select>
</label>
<label for="subscribe">
<input id="subscribe" type="checkbox" name="cf" value="check" checked>
Send me your newsletter</label>
<label for="sales">
<label for="support">
<input id="slsSupport" type="radio" name="cf" value="sales" checked>Sales
<input id="slsSupport" type="radio" name="cf" value="support">Support
</label>
</label>
<label for="msg">Message:</label>
<textarea id="msg" name="cf" rows="10" cols="30" required></textarea>
</fieldset>
<fieldset>
<button type="submit">Send</button>
<button type="reset">Reset</button>
</fieldset>
</form>
<script src="contactform_Lab8.js"></script>
</body>
</html>
Try
// Var for element
var contactname = document.getElementsByName("cf");
//Get value when clicking out of field
Array.prototype.slice.call(contactname).forEach(function(elem, index) {
elem.addEventListener("change",function(event) {
// `log` `elem` `index` , `id` , `value`
console.log(index, event.target.id, event.target.value);
}, false);
});
<form id="contactus">
<fieldset>
<label for="name">Name:</label>
<input id="name" type="text" name="cf" autofocus required>
<label for="email">Email:</label>
<input id="email" type="email" name="cf" required>
<label for="phone">Phone:</label>
<input id="phone" type="tel" name="cf" required>
<label for="status">Status:
<select id="status" name="cf" required>
<option value="client">Client</option>
<option value="partner">Partner</option>
<option value="vendor">Vendor</option>
</select>
</label>
<label for="subscribe">
<input id="subscribe" type="checkbox" name="cf" value="check" checked>
Send me your newsletter</label>
<label for="sales">
<label for="support">
<input id="slsSupport" type="radio" name="cf" value="sales" checked>Sales
<input id="slsSupport" type="radio" name="cf" value="support">Support
</label>
</label>
<label for="msg">Message:</label>
<textarea id="msg" name="cf" rows="10" cols="30" required></textarea>
</fieldset>
<fieldset>
<button type="submit">Send</button>
<button type="reset">Reset</button>
</fieldset>
</form>

Categories