Radio button validation and Selector list validation in jQuery - javascript

$(document).ready(function () {
$("#mysubmit").click(function (){
$("#first_name").text("");
$("#last_name").text("");
$("#message").text("");
var myFirst = $("#first_name").val();
var fName = "";
var myLast = $("#last_name").val();
var lName = "";
var radioVal = $("input[name='gender']:checked").val();
var myGender = "";
var years = $("#years option:selected").val();
var myYears = "";
if (myFirst == "")
{
$("#first_error").text("You must Enter a First Name");
$("#first_name").focus();
}
else {
fName += "Employment Stats for " + $("#first_name").val() + " ";
}
if (myFirst !== "" && myLast == "")
{
$("#first_error").text("");
$("#last_error").text("You must Enter a Last Name");
$("#last_name").focus();
}
else {
lName += $("#last_name").val();
}
if (myLast !== "" & radioVal == "")
{
$("#gender_error").text("You must choose a Gender");
return false;
}
else {
console.log(radioVal)
myGender += "You are a: " + radioVal;
}
if (radioVal !== "" && years == "-")
{
$("#years_error").text("You Must enter amount of Years");
}
else {
myYears += $("#years").text("You have: " + years + " years experience");
console.log(years)
}
//yellow textbox for end message after submit
if (myFirst !== "" && myLast !== "" && myGender !== "" && years !== "-")
{
$("#message").css("backgroundColor", "yellow");
$("#message").text(fName + lName + myGender + myYears);
}
})
})
/* type selectors */
article, aside, figure, figcaption, footer, header, nav, section {
display: block;
}
* {
margin: 10;
padding: 10;
}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
width: 650px;
background-color: silver;
}
h1 {
font-size: 150%;
}
h2 {
font-size: 120%;
padding: .25em 0 .25em 25px;
}
p {
padding-bottom: .25em;
padding-left: 25px;
}
.error {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Assignment 6</title>
<link rel="stylesheet" href="Assignment_6.css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="Assignment_6.js"></script>
</head>
<body>
<div id="top">
<h1>Assignment 6</h1>
<h3>Enter Employment Statistics</h3>
<form>
<br>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" required> <span class="error" id="first_error"></span>
<br>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name" required> <span class="error" id="last_error"></span>
<br>
Male <input type="radio" name="gender" value="M">
Female <input type="radio" name="gender" value="F"> <span class="error" id="gender_error"></span>
<br>
Years Experience:
<select id="years" size="1">
<option value="-">-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<span class="error" id="years_error"></span>
<br><br>
<input type="button" id="mysubmit" value="Submit Form">
<br>
</form>
</div>
<div id="message">
</div>
</body>
</html>
I'm having trouble figuring out form validation using jQuery. I'm supposed to have an error message pop up one by one in the fields if something is not filled out.
For example, if the first name is not filled out, on submit it shows the error message for first name and so forth for the rest.
I'm having issues getting the radio button and the selector list to show an error message and to retrieve the value to then place into my end message. Would anyone be able to assist me with this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Assignment 6</title>
<link rel="stylesheet" href="Assignment_6.css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="Assignment_6.js"></script>
</head>
<body>
<div id="top">
<h1>Assignment 6</h1>
<h3>Enter Employment Statistics</h3>
<form>
<br>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" required> <span class="error" id="first_error"></span>
<br>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name" required> <span class="error" id="last_error"></span>
<br>
Male <input type="radio" name="gender" value="M">
Female <input type="radio" name="gender" value="F"> <span class="error" id="gender_error"></span>
<br>
Years Experience:
<select id="years" size="1">
<option value="-">-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<span class="error" id="years_error"></span>
<br><br>
<input type="button" id="mysubmit" value="Submit Form">
<br>
</form>
</div>
<div id="message">
</div>
</body>
</html>
js:
$(document).ready(function () {
$("#mysubmit").click(function (){
$("#first_name").text("");
$("#last_name").text("");
$("#message").text("");
var myFirst = $("#first_name").val();
var fName = "";
var myLast = $("#last_name").val();
var lName = "";
var radioVal = $("input[name='gender']:checked").val();
var myGender = "";
var years = $("#years option:selected").val();
var myYears = "";
if (myFirst == "")
{
$("#first_error").text("You must Enter a First Name");
$("#first_name").focus();
}
else {
fName += "Employment Stats for " + $("#first_name").val() + " ";
}
if (myFirst !== "" && myLast == "")
{
$("#first_error").text("");
$("#last_error").text("You must Enter a Last Name");
$("#last_name").focus();
}
else {
lName += $("#last_name").val();
}
if (myLast !== "" & radioVal == "")
{
$("#gender_error").text("You must choose a Gender");
return false;
}
else {
console.log(radioVal)
myGender += "You are a: " + radioVal;
}
if (radioVal !== "" && years == "-")
{
$("#years_error").text("You Must enter amount of Years");
}
else {
myYears += $("#years").text("You have: " + years + " years experience");
console.log(years)
}
//yellow textbox for end message after submit
if (myFirst !== "" && myLast !== "" && myGender !== "" && years !== "-")
{
$("#message").css("backgroundColor", "yellow");
$("#message").text(fName + lName + myGender + myYears);
}
})
})
css:
/* type selectors */
article, aside, figure, figcaption, footer, header, nav, section {
display: block;
}
* {
margin: 10;
padding: 10;
}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
width: 650px;
background-color: silver;
}
h1 {
font-size: 150%;
}
h2 {
font-size: 120%;
padding: .25em 0 .25em 25px;
}
p {
padding-bottom: .25em;
padding-left: 25px;
}
.error {
color: red;
}

The issue is you're testing for a blank value, when what is actually getting returned is undefined. That is because you're asking for the value of something that doesn't yet exist - in this case, a selected radio button.
When no radio button is selected, there is no value for
var radioVal = $("input[name='gender']:checked").val(); and so it's undefined.
I see you have a variable ready, but it's testing the wrong thing, here is my suggested change:
var radioVal = $("input[name='gender']:checked");
// this creates an array of elements
var genderIsSelected = radioVal.length > 0;
// if that array has something in it, the gender was selected
var myGender = genderIsSelected ? radioVal[0].val() : '';
// populate myGender with the actual value, or blank
The same error is happening for your select menu validation.

Related

How can i format the template in which the data gets downloaded in the text blob through javascript in an HTML Form?

I have a web app downloads the user input in form of a text file. How can I modify the template of the text file which is getting downloaded. Is there any way.
The current format in which it is getting downloaded is:-
Name: Mike
Email: xyz#gmail.com
Test type: BFT
Product Type: RAID
Protocol Type: iSCSI
IP Address: 255.255.255.0
Chasis Inputs: 21
HBA_Ports:
MC_IP:
MC_Netmask:
MC_Gateway:
MC:
SC:
FU:
EC:
Controller_ID:
The expected way I am looking for it to download is
Name: Mike
Email: xyz#gmail.com
Test type: BFT
IP Address: 255.255.255.0
product Type: RAID
Protocol Type: iSCSI
-Controller_ID:
-Chasis Inputs: 21
-HBA_Ports:
-MC_IP:
-MC_Netmask:
-MC_Gateway:
-MC:
-SC:
-FU:
-EC:
<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<h1>User Information</h1>
<style>
html,
html * {
box-sizing: border-box;
border-color: teal;
font-family: calibri;
}
html {
background: radial-gradient(
rgba(48, 97, 97, 0.5),
rgba(255, 255, 255, 0.5)
);
}
input[type="button"],
input[type="submit"] {
padding: 1rem;
}
input[type="text"],
textarea,
select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid rgb(19, 18, 18);
border-radius: 4px;
color: teal;
}
fieldset {
border: none;
padding: 10px;
overflow: hidden;
color: rgb(16, 8, 32);
font-size: 25px;
font-style: initial;
font-family: "Times New Roman", Times, serif;
}
#extra {
border: 2px solid black;
background: whitesmoke;
border-radius: 1rem;
box-shadow: 0 0 5px black;
width: calc(100% - 24px);
margin: auto;
float: none;
clear: both;
}
#extra h6 {
margin: 0;
}
.invalid {
border: 2px solid red !important;
background: rgba(255, 0, 0, 0.1);
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
const extra = {};
const oForm = document.forms.myForm;
const oSave = document.querySelector('input[name="save"]');
const oSub = document.querySelector('input[name="submit"]');
const oCtrl = document.querySelector('select[name="controller"]');
const oTest = document.querySelector('select[name="test"]');
const oProto = document.querySelector('select[name="protocol"]');
const oTmp = document.querySelector("template");
const changehandler = function(e) {
let option = this.options[this.options.selectedIndex];
if (option.hasAttribute("data-extra")) extra[this.name] = this.value;
else {
if (extra.hasOwnProperty(this.name)) delete extra[this.name];
}
if (Object.keys(extra).length == 2) {
let fieldset = oTmp.content.cloneNode(true);
oForm.insertBefore(fieldset, oProto.parentNode.nextSibling);
} else {
if (document.getElementById("extra")) {
fieldset = document.getElementById("extra");
fieldset.parentNode.removeChild(fieldset);
}
}
if (option.hasAttribute("data-extra")) extra[this.name] = this.value;
else {
if (extra.hasOwnProperty(this.name)) delete extra[this.name];
}
/*
if( option.hasAttribute( 'data-RBOD' ) ) extra[ this.name ]=this.value;
else{
if( extra.hasOwnProperty( this.name ) )delete extra[ this.name ];
}
*/
if (this.name == "controller") {
if (this.value == "RAID") oProto.disabled = false;
else oProto.disabled = true;
}
};
const dialog = function(msg) {
alert(msg);
return false;
};
const savehandler = function(e) {
e.preventDefault();
let valid = true;
/*[ 'name','email','test','controller','ip','chassis' ].forEach( n => {
oForm[ n ].classList.remove('invalid');
if( oForm[ n ].value=='' ){
oForm[ n ].classList.add('invalid');
valid=false;
}
});*/
if (!valid) return dialog("Please fill all the fields!");
const reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(oForm.email.value) == false) {
return dialog("Invalid Email Address");
}
const ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipformat.test(oForm.ip.value) == false) {
return dialog("Invalid IP Address");
}
if (oForm.name.value.length < 3)
return dialog("Name must be having atleast 3 Characters");
let data = {
Name: oForm.name.value,
Email: oForm.email.value,
"Test type": oForm.test.value,
"Product Type": oForm.controller.value,
"Protocol Type": oForm.protocol.value,
"IP Address": oForm.ip.value,
"Chasis Inputs": oForm.chassis.value
};
if (Object.keys(extra).length == 2) {
data["HBA_Ports"] = oForm["hba-ports"].value;
data["MC_IP"] = oForm["extra-ip"].value;
data["MC_Netmask"] = oForm["netmask-ip"].value;
data["MC_Gateway"] = oForm["gateway-ip"].value;
data["MC"] = oForm["rbod-mc"].value;
data["SC"] = oForm["rbod-sc"].value;
data["FU"] = oForm["rbod-fu"].value;
data["EC"] = oForm["rbod-ec"].value;
data["Controller_ID"] = oForm["Controller-ID"].value;
}
let payload = Object.keys(data)
.map(key => {
return [key, data[key]].join(": ");
})
.join(String.fromCharCode(10));
const blob = new Blob([payload], { type: "text/plain" });
const file = "formData.yaml";
let link = document.createElement("a");
link.download = file;
if (window.webkitURL != null) {
link.href = window.webkitURL.createObjectURL(blob);
} else {
link.href = window.URL.createObjectURL(blob);
link.style.display = "none";
document.body.appendChild(link);
}
link.click();
};
oCtrl.addEventListener("change", changehandler);
oTest.addEventListener("change", changehandler);
oSave.addEventListener("click", savehandler);
});
</script>
</head>
<body>
<template>
<fieldset id="extra">
<h6>Additional Details Required</h6>
<label for="Controller_ID">Controller_ID:</label>
<select name="Controller-ID" required>
<option value=""> - Select the Controller ID - </option>
<option value="A">A </option
><option value="B">B </option></select
>
<label for="HBA_Ports">HBA_Ports:</label
><input
type="text"
name="hba-ports"
placeholder="Enter the HBA Ports"
/>
<label for="MC_IP">MC_IP:</label
><input type="text" name="extra-ip" placeholder="Enter the MC_IP" />
<label for="MC_Netmask">MC_Netmask:</label
><input
type="text"
name="netmask-ip"
placeholder="Enter the MC_Netmask"
/>
<label for="MC_Gateway">MC_Gateway:</label
><input
type="text"
name="gateway-ip"
placeholder="Enter the MC_Gateway"
/>
<label for="MC">MC:</label
><input type="text" name="rbod-mc" placeholder="Enter the MC Port" />
<label for="SC">SC:</label
><input type="text" name="rbod-sc" placeholder="Enter the SC Port" />
<label for="FU">FU:</label
><input type="text" name="rbod-fu" placeholder="Enter the FU Port" />
<label for="EC">EC:</label
><input type="text" name="rbod-ec" placeholder="Enter the EC Port" />
</fieldset>
</template>
<form name="myForm" method="POST">
<fieldset>
<label for="Name">Name</label>
<input type="text" name="name" placeholder="Enter your name" required />
</fieldset>
<fieldset>
<label for="Email">Email</label>
<input
type="text"
name="email"
placeholder="Enter your Email Id"
required
/>
</fieldset>
<fieldset>
<label for="Controller Type">Controller Type</label>
<select name="controller" required>
<option value=""> - Select the Controller - </option>
<option data-extra="true" value="RAID">RAID </option
><option value="JBOD">JBOD </option
><option value="AP">AP </option></select
>
</fieldset>
<fieldset>
<label for="Test Type">Test Type</label>
<select name="test" required>
<option value=""> - Select The Test - </option>
<option data-extra="true" value="BFT">BFT </option
><option data-extra="true" value="CTO">CTO </option
><option data-extra="true" value="RAID Generic">RAID Generic </option
><option data-extra="true" value="Port Check">Port Check </option
><option data-extra="true" value="FW Generic">FW Generic </option
><option data-extra="true" value="JBOD Generic"
>JBOD Generic
</option></select
>
</fieldset>
<!-- insert templated additional details here -->
<fieldset>
<label for="Protocol Type">Protocol Type</label>
<select name="protocol" disabled>
<option selected hidden disabled> - Select The Protocol - </option
><option data-extra="true" value="SAS">SAS </option
><option data-extra="true" value="iSCSI">iSCSI </option
><option data-extra="true" value="FC">FC </option></select
>
</fieldset>
<fieldset>
<label for="IP Address">IP Address:</label>
<input
type="text"
name="ip"
placeholder="Enter your IP address"
required
/>
</fieldset>
<fieldset>
<label for="Chasis Input">Number of Chasis Input:</label>
<input
type="number"
name="chassis"
placeholder="Enter Number of Chasis"
required
/>
</fieldset>
<fieldset>
<input type="button" name="save" value="Save data to file" />
</fieldset>
</form>
</body>
</html>

Unable to redirect my form to a new html page. Its going to localhost:3000/confirm.html instead i want it to open confirm.html in a new window

In the below code, after clicking on 'Save Data' I want the page to go to another htm page 'confrim.html'. Instead what is happening is its just showing "localhost:3000/confirm.html" and not opening a new page. Can anyone help to fix this, attaching the code for the reference.
I tried to implement the following through the submitInfo() function
Thanks
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">-->
<style>
* {
box-sizing:border-box;
border-color: teal;
}
html{
background : radial-gradient(rgba(48, 97, 97, 0.5),rgba(255,255,255,0.5))
}
div {
padding: 10px;
overflow: hidden;
color: rgb(16, 8, 32);
font-size: 25px;
font-style: initial;
font-family: 'Times New Roman', Times, serif;
}
.input[type=button]{
font: 25px Calibri;
width: auto;
float: left;
cursor: pointer;
padding: 7px;
color: teal;
font-size: 30px;
}
#bt{
width : 190px;
height: 60px;
font-size: 25px;
font-family: 'Times New Roman', Times, serif;
background-color: #05193d;
color: whitesmoke;
box-shadow: 0 2px 2px 0 rgba(0,0,0,0.5);
margin-top: 10px;
}
input[type=text], textarea, select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid rgb(19, 18, 18);
border-radius: 4px;
color:teal
}
</style>
<title>Save form Data in a Text File using JavaScript</title>
<h1>User Information </h1>
<!--<link rel="stylesheet" href="style.css">-->
</head>
<body>
<div>
<form name="myForm" action="confirm.html" method="POST" >
<!--Add few elements to the form-->
<div>
<label for="Name">Name</label>
<input type="text" id="txtName" placeholder="Enter your name" required />
</div>
<div>
<label for="Email">Email</label>
<input type="text" id="txtEmail" placeholder="Enter your Email Id" />
</div>
<div>
<label for="Controller Type">Controller Type</label>
<select id="selProd">
<option value=""> - Select the Controller - </option>
<option value="RAID">RAID</option>
<option value="JBOD">JBOD</option>
<option value="EBOD">EBOD</option>
<option value="AP">AP</option>
</select>
</div>
<div>
<label for="Test Type">Test Type </label>
<select id="selTest">
<option value=""> - Select The Test - </option>
<option value="BFT">BFT</option>
<option value="Manufacturing">Manufacturing</option>
<option value="Channel">Channel</option>
<option value="DVT" >DVT</option>
</select>
</div>
<div>
<label for="Protocol Type">Protocol Type </label>
<select id="selProto">
<option value=""> - Select The Protocol - </option>
<option value="SAS">SAS</option>
<option value="iSCSI">iSCSI</option>
<option value="FC">FC</option>
</select>
</div>
<div>
<label for="IP Address">IP Address:</label>
<input type="text" id="txtIP" placeholder="Enter your IP address" />
</div>
<div>
<label for="Chasis Input">Number of Chasis Input:</label>
<input type="number" id="txtInputs" placeholder="Enter Number of Chasis" />
</div>
<div>
<input type="button" id="myBtn" value="Save data" onclick="submitInfo()"/>
</div>
<div>
<input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
</div>
</form>
</div>
<script>
let saveFile = () => {
// Get the data from each element on the form.
const name = document.getElementById('txtName');
const email = document.getElementById('txtEmail');
const test = document.getElementById('selTest');
const product = document.getElementById('selProd');
const protocol = document.getElementById('selProto');
const IP = document.getElementById('txtIP');
const Inputs = document.getElementById('txtInputs');
// This variable stores all the data.
let data =
'\rName : ' + name.value + '\r\n' +
'Email ID : ' + email.value + '\r\n' +
'Test Type : ' + test.value + '\r\n' +
'Product Type : ' + product.value + '\r\n' +
'Protocol Type : ' + protocol.value + '\r\n' +
'IP Address : ' + IP.value + '\r\n' +
'Chasis Inputs : ' + Inputs.value;
if(name.value =='' || email.value == '' || test.value =='' || product.value =='' || IP.value == ''|| Inputs.value == ''){
alert("Please fill all the fields!");
return;
}
const reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == false)
{
alert('Invalid Email Address');
return false;
}
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipformat.test(IP.value) == false)
{
alert('Invalid IP Address');
return false;
}
if(name.value.length<3){
alert("Name must be having atleast 3 Characters");
return;
}
if(name.value == ''){
alert("Enter the name First");
}
// Convert the text to BLOB.
const textToBLOB = new Blob([data], { type: 'text/plain' });
const sFileName = 'formData.yaml'; // The file to save the data.
let newLink = document.createElement("a");
newLink.download = sFileName;
if (window.webkitURL != null) {
newLink.href = window.webkitURL.createObjectURL(textToBLOB);
}
else {
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
}
newLink.click();
}
var disable_options = false;
document.getElementById('selProd').onchange = function () {
//alert("selected value = "+this.value);
if(this.value == "RAID")
{
document.getElementById('selProto').removeAttribute('disabled');
}
else
{
document.getElementById('selProto').setAttribute('disabled', true);
}
}
function submitInfo(){
var test = document.getElementById('selTest').value;
var product = document.getElementById('selProd').value;
if(product == "EBOD" && test== "BFT"){
window.location ="confirm.html";
}
}
</script>
</body>
</html>
You could use the window.open method - like so:
function submitInfo(){
var test = document.getElementById('selTest').value;
var product = document.getElementById('selProd').value;
if( product == "EBOD" && test== "BFT" ){
window.open( "confirm.html", "Confirm", "fullscreen=yes,location=no,menubar=yes,resizable=no,scrollbars=no,status=no,toolbar=no" );
}
}
you have a
<form name="myForm" action="confirm.html" method="POST" >
which, on form submit, your browser will look for confirm.html file. I don't know whether you have file named confirm.html, but I think you do. otherwise it'll show 404 error.
As you instructed in your form, browser'll look for confirm.html, and on redirect, it'll show what's in confirm.html file.
you should remove your js script from this file and put it inside confirm.html file. or just replace action="confirm.html" with action=""

The form just don't submit even if after all field is filled and checked

I am a beginner student in web design and this is a project I was given but no matter what I do the form just won't submit. even if all the input is correct it still doesn't do anything after I click submit. Any help is appreciated. I have googled for an hour but nothing I do works.
This is just a simple structure of a form. My main goal is to validate the code and sent to a PHP script.
<html>
<head>
<title>Form</title>
<style>
h1,h2 {
color:red;
text-align:center;
}
#form {
padding-left: 80px;
}
.fullname{
//border:1px solid;
padding:0 0 0 80px;
margin:0;
color:red;
font-style:italic;
font-size:13px;
white-space:nowrap;
//float:left;
//visibility:hidden;
}
.N {
//border-color:red;
border-radius:5px;
//text-shadow:0 0 2px #ddd;
}
</style>
</head>
<body>
<h1>Welcome</h1>
<!--onSubmit="return !!(validateFName() & validateLName() & validateGender() & validateMonth() & validateDay() & validateYear());" -->
<form id="form" name="myForm" action="new1.php" onSubmit="return validateName()" >
First Name:<input class="N" type="text" name="fname" value="enter name
here" /><br>
<div id="errorFName" class="fullname"></div>
Last Name:<input class="N" type="text" name="lname" value="enter name here"/><br>
<div id="errorLName" class="fullname"></div>
Gender:<br>
<input type="radio" name="sex" value="Male">Male
<input type="radio" name="sex" value="Female">Female<br>
<div id="gender" class="fullname" style="padding:0 0 0 15px;"></div>
Date Of Birth:<br>
Month:
<select name="month">
<option value="0">--Select Month--</option>
<option value="1">Janaury</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
 
Day:
<select name="day">
<option value='No'>--Select Day--</option>
<option value='Mo'>Monday</option>
<option value='tu'>Tuesday</option>
<option value='we'>Wednesday</option>
<option value='th'>Thursday</option>
<option value='fr'>Friday</option>
<option value='sa'>Saturday</option>
<option value='su'>Sunday</option>
</select>
 
Year:
<select name="year">
<script>
for(var i = 2017; i >= 1900; i--){
document.write('<option value="'+i+'">'+i+'</option>');
}
</script>
</select>
<br>
<span id="month_div" class="fullname" style="padding:0 0 0 60px;"></span>
<span id="day_div" class="fullname" style="padding:0 0 0 80px;"></span>
<span id="year_div" class="fullname" style="padding:0 0 0 65px;"></span><br>
<input type="submit" value="Submit">
</form>
<script>
var firstName = document.forms.myForm.fname;
var lastName = document.forms.myForm.lname;
var gender = document.forms.myForm.sex;
var months = document.forms.myForm.month;
var days = document.forms.myForm.day;
var years = document.forms.myForm.year;
var fname_error = document.getElementById("errorFName");
var lname_error = document.getElementById("errorLName");
var gender_error = document.getElementById("gender");
var month_error = document.getElementById("month_div");
var day_error = document.getElementById("day_div");
var year_error = document.getElementById("year_div");
function validateName() {
var validity = true;
validity &= validateFName();
validity &= validateLName();
validity &= validateGender();
validity &= validateMonth();
validity &= validateDay();
validity &= validateYear();
return validity;
}
function validateFName() {
if (firstName.value === "enter name here") {
firstName.value = "";
firstName.style.border = "1px solid red";
fname_error.textContent = "Fill User Name";
return false;
}
if (firstName.value !== "enter name here") {
// fname_error.innerHTML = "";
return true;
}
}
function validateLName() {
if (lastName.value === "enter name here") {
lastName.value = "";
lastName.style.border = "1px solid red";
lname_error.textContent = "Fill User Name";
return false;
}
}
function validateGender() {
if (gender[0].checked || gender[1].checked) {
gender_error.innerHTML = "";
return true;
} else {
gender_error.textContent = "select your sex";
return false;
}
}
function validateMonth() {
if (months.value !== "0") {
month_error.innerHTML = "";
day_error.style.padding = "0 0 0 175px";
return true;
} else {
month_error.textContent = "select the month";
return false;
}
}
function validateDay() {
if (days.value !== "No") {
day_error.innerHTML = "";
year_error.style.padding = "0 0 0 150px";
return true;
} else {
day_error.textContent = "select the day";
//day_error.style.padding = "0 0 0 80px";
return false;
}
}
function validateYear() {
if (years.value !== "2017") {
year_error.innerHTML = "";
return true;
} else {
year_error.textContent = "select the year";
return false;
}
}
</script>
</body>
</html>
edit: just tried to debug it this way and it seems that the code just passed through even if the return value is true.
the out put is always "it doesnt work"
function validateName() {
var validity = true;
validity &= validateFName();
if (validity === true)
alert("it works FName");
validity &= validateLName();
if (validity === true)
alert("it works LName");
validity &= validateGender();
if (validity === true)
alert("it works Gender");
validity &= validateMonth();
if (validity === true)
alert("it works Month");
validity &= validateDay();
if (validity === true)
alert("it works Day");
validity &= validateYear();
alert("it works Year");
if (validity === true)
return validity;
else
alert("it dosnt works");
}
edit 2. now my problem is with submit. it submits the form without validating any input. it should say "please fill the fields" but it just goes to the php file.
check this code , hope it will work, i update your some code and use placeholder so no need to use check using text and update &= to = and related some code , hope it will work now
<html>
<head><title>Form</title>
<style>
h1, h2 {
color: red;
text-align: center;
}
#form {
padding-left: 80px;
}
.fullname {
/ / border: 1 px solid;
padding: 0 0 0 80px;
margin: 0;
color: red;
font-style: italic;
font-size: 13px;
white-space: nowrap;
/ / float: left;
/ / visibility: hidden;
}
.N {
/ / border-color: red;
border-radius: 5px;
/ / text-shadow: 0 0 2 px #ddd;
}
</style>
</head>
<body>
<h1>Welcome</h1>
<!--onSubmit="return !!(validateFName() & validateLName() & validateGender() & validateMonth() & validateDay() & validateYear());" -->
<form id="form" name="myForm" action="" method="post" onSubmit="return validateName()">
First Name:<input class="N" type="text" name="fname" value="" placeholder="enter namehere"/><br>
<div id="errorFName" class="fullname"></div>
Last Name:<input class="N" type="text" name="lname" value="" placeholder="enter name here"/><br>
<div id="errorLName" class="fullname"></div>
Gender:<br>
<input type="radio" name="sex" value="Male">Male
<input type="radio" name="sex" value="Female">Female<br>
<div id="gender" class="fullname" style="padding:0 0 0 15px;"></div>
Date Of Birth:<br>
Month:
<select name="month">
<option value="0">--Select Month--</option>
<option value="1">Janaury</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select> 
Day:
<select name="day">
<option value='No'>--Select Day--</option>
<option value='Mo'>Monday</option>
<option value='tu'>Tuesday</option>
<option value='we'>Wednesday</option>
<option value='th'>Thursday</option>
<option value='fr'>Friday</option>
<option value='sa'>Saturday</option>
<option value='su'>Sunday</option>
</select> 
Year:
<select name="year">
<script>
for (var i = 2017; i >= 1900; i--) {
document.write('<option value="' + i + '">' + i + '</option>');
}
</script>
</select><br>
<span id="month_div" class="fullname" style="padding:0 0 0 60px;"></span>
<span id="day_div" class="fullname" style="padding:0 0 0 80px;"></span>
<span id="year_div" class="fullname" style="padding:0 0 0 65px;"></span><br>
<input type="submit" value="Submit">
</form>
<script>
var firstName = document.forms.myForm.fname;
var lastName = document.forms.myForm.lname;
var gender = document.forms.myForm.sex;
var months = document.forms.myForm.month;
var days = document.forms.myForm.day;
var years = document.forms.myForm.year;
var fname_error = document.getElementById("errorFName");
var lname_error = document.getElementById("errorLName");
var gender_error = document.getElementById("gender");
var month_error = document.getElementById("month_div");
var day_error = document.getElementById("day_div");
var year_error = document.getElementById("year_div");
function validateName() {
validity = true;
validity = validateFName();
validity = validateLName();
validity = validateGender();
validity = validateMonth();
validity = validateDay();
validity = validateYear();
// return validity;
if(validateFName() && validateLName() && validateGender() && validateMonth() && validateYear()){
document.getElementById("form").action = "http://localhost/new1.php";
// change this url which your action
document.getElementById("form").submit();
} else {
return false;
}
}
function validateFName() {
if (firstName.value == "") {
firstName.value = "";
firstName.style.border = "1px solid red";
fname_error.textContent = "Fill User Name";
return false;
} else {
fname_error.textContent = "";
firstName.style.border = "1px solid #fff";
return true;
}
}
function validateLName() {
if (lastName.value == "") {
lastName.value = "";
lastName.style.border = "1px solid red";
lname_error.textContent = "Fill User Name";
return false;
} else {
lname_error.textContent = "";
lastName.style.border = "1px solid #fff";
return true;
}
}
function validateGender() {
if (gender[0].checked || gender[1].checked) {
gender_error.innerHTML = "";
return true;
}
else {
gender_error.textContent = "select your sex";
return false;
}
}
function validateMonth() {
if (months.value !== "0") {
month_error.innerHTML = "";
day_error.style.padding = "0 0 0 175px";
return true;
}
else {
month_error.textContent = "select the month";
return false;
}
}
function validateDay() {
if (days.value !== "No") {
day_error.innerHTML = "";
year_error.style.padding = "0 0 0 150px";
return true;
}
else {
day_error.textContent = "select the day";
//day_error.style.padding = "0 0 0 80px";
return false;
}
}
function validateYear() {
if (years.value !== "2017") {
year_error.innerHTML = "";
return true;
}
else {
year_error.textContent = "select the year";
return false;
}
}
</script>
</body>
</html>
Use
var firstName = document.forms.myForm.fname.value;
You have forgot to add value after field name.

Confirm Message Box Issue and Reset Button Issue

My question is twofold. First, I can't seem to figure out how to get my confirm message box's ok and cancel to work correctly. The assignment calls for me to run the message, then validate my info, and if it validates, alert for ok or cancel. I have done it the other way around (validate....message....alert), but I'm not sure how to do this.
Second, my reset button clears my info whether I hit ok or cancel??? Any ideas?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!--Document Head-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!--Title Element-->
<title>Greendale Community College</title>
<!--Style Element-->
<style type="text/css">
body {
background-color: white;
}
h1 {
text-align: center;
font-family: Impact;
color: green;
}
p {
font-size: 36px;
color: green;
}
</style>
<!--Script Element-->
<script type="text/javascript">
/* <![CDATA[ */
function submitRegistration() {
var fName = document.registration.firstName.value;
var lName = document.registration.lastName.value;
var cwid = document.registration.cwid.value;
var semester = document.registration.semester.value;
var course = document.registration.courses.value;
var section = document.registration.section.value;
var major = document.registration.needForMajor.value;
var semesterDisplay;
if (semester == "fall")
semesterDisplay = "Fall";
if (semester == "spring")
semesterDisplay = "Spring";
if (semester == "summer")
semesterDisplay = "Summer";
var checkDisplay;
if (document.registration.needForMajor.checked == true) {
checkDisplay = "Course Needed For Major";
}
else {
checkDisplay = "";
}
window.confirm("Student Name: " + fName + " " + lName + " CWID: " + cwid + " Semester: " + semesterDisplay + " Course: " + course + " Section: " + section + " " + checkDisplay);
if (fName == "") {
window.alert("You must enter your first name!");
return false;
}
if (isNaN(fName) == false) {
window.alert("Your First Name must be non-numeric values!");
return false;
}
if (lName == "") {
window.alert("You must enter your last name!");
return false;
}
if (isNaN(lName) == false) {
window.alert("Your Last Name must be non-numeric values!");
return false;
}
if (cwid == "") {
window.alert("You must enter your cwid!");
return false;
}
if (isNaN(cwid) == true) {
window.alert("Your CWID must be numeric values!");
return false;
}
var validateSemester = false;
for (var i = 0; i < 3; ++i) {
if (document.registration.semester[i].checked == true) {
validateSemester = true;
break;
}
}
if (validateSemester != true) {
window.alert("You must select a Semester!");
return false;
}
if (course == "") {
window.alert("You must select a Course!");
return false;
}
if (section == "") {
window.alert("You must select a Section!");
return false;
}
if (true) {
window.alert("You have been registered for your course!");
}
else {
window.alert("Your registration has been canceled.");
}
}
function resetRegistration() {
var resetForm = window.confirm("Are you sure you want to reset the form?");
if (resetForm == true)
return true;
return false;
}
/* ]]> */
</script>
</head>
<body>
<!--Heading Element-->
<h1>Greendale Community College</h1>
<center><img src="greendale.jpg" alt="greendale" width="512" height="256" /></center>
<h2 align="center">Course Registration Page</h2>
<form action="FormProcessor.html" name="registration" method="get"
onsubmit="submitRegistration();"
onreset="resetRegistration()">
<h3>Student Information Form</h3>
<!--Student Information-->
First Name:<input type="text" name="firstName"><br>
Last Name:<input type="text" name="lastName"><br>
CWID:<input type="text" name="cwid"><br>
<h3>Semester</h3>
<h4>(choose a semester)</h4>
<!--Radio Buttons to Choose Semester-->
<input type="radio" name="semester" value="fall" /> Fall 2018 <br />
<input type="radio" name="semester" value="spring" /> Spring 2018 <br />
<input type="radio" name="semester" value="summer" /> Summer 2018 <br />
<h3>Courses</h3>
<h4>(choose one course)</h4>
<table>
<!--Drop Down Box for Courses-->
<tr><td style="background:white;border:0">Courses:</td>
<tr>
<td>
<select name="courses" size="1">
<option value=""></option>
<option value="CIS 110">Intro to CIS</option>
<option value="CIS 120">Application Prog I</option>
<option value="CIS 299">System Analysis I</option>
<option value="CIS 330">Web Programming I</option>
<option value="CIS 304">Cobol</option>
</select>
</td>
</tr>
</table>
<h3>Sections</h3>
<h4>(choose one section)</h4>
<table>
<tr><td style="background:white;border:0">Section Numbers:</td>
<tr>
<td>
<select name="section" multiple="multiple" size="5">
<option value="001">CIS 110 001</option>
<option value="gw1">CIS110 GW1</option>
<option value="001">CIS 120 001</option>
<option value="gw1">CIS 120 GW1</option>
<option value="gw1">CIS 302 GW1</option>
<option value="001">CIS 304 001</option>
<option value="gw1">CIS 303 GW1</option>
<option value="001">CIS 321 001</option>
<option value="gw1">CIS 321 GW1</option>
<option value="gw1">CIS 322 GW1</option>
</select>
</td>
</tr>
</table>
<input type="checkbox" name="needForMajor" />
Check if the course is required for your major!<br />
<!--Submit and Reset Buttons Created-->
<input type="submit" name="submit" onsubmit="submitRegistration();" value="Submit"><br />
<input type="reset" name="reset" onreset="resetRegistration();" value="Reset">
</form>
</body>
</html>
I got it: I forgot to use return:
<form action="FormProcessor.html" name="registration" method="get"
onsubmit="return submitRegistration();"
onreset="return resetRegistration()">
instead of:
<form action="FormProcessor.html" name="registration" method="get"
onsubmit="submitRegistration();"
onreset="resetRegistration()">
Try below solution. It should work.
<html xmlns="http://www.w3.org/1999/xhtml">
<!--Document Head-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!--Title Element-->
<title>Greendale Community College</title>
<!--Style Element-->
<style type="text/css">
body {
background-color: white;
}
h1 {
text-align: center;
font-family: Impact;
color: green;
}
p {
font-size: 36px;
color: green;
}
</style>
<!--Script Element-->
<script type="text/javascript">
/* <![CDATA[ */
function submitRegistration() {
var fName = document.registration.firstName.value;
var lName = document.registration.lastName.value;
var cwid = document.registration.cwid.value;
var semester = document.registration.semester.value;
var course = document.registration.courses.value;
var section = document.registration.section.value;
var major = document.registration.needForMajor.value;
var semesterDisplay;
if (semester == "fall")
semesterDisplay = "Fall";
if (semester == "spring")
semesterDisplay = "Spring";
if (semester == "summer")
semesterDisplay = "Summer";
var checkDisplay;
if (document.registration.needForMajor.checked == true) {
checkDisplay = "Course Needed For Major";
}
else {
checkDisplay = "";
}
if (fName == "") {
window.alert("You must enter your first name!");
return false;
}
if (isNaN(fName) == false) {
window.alert("Your First Name must be non-numeric values!");
return false;
}
if (lName == "") {
window.alert("You must enter your last name!");
return false;
}
if (isNaN(lName) == false) {
window.alert("Your Last Name must be non-numeric values!");
return false;
}
if (cwid == "") {
window.alert("You must enter your cwid!");
return false;
}
if (isNaN(cwid) == true) {
window.alert("Your CWID must be numeric values!");
return false;
}
var validateSemester = false;
for (var i = 0; i < 3; ++i) {
if (document.registration.semester[i].checked == true) {
validateSemester = true;
break;
}
}
if (validateSemester != true) {
window.alert("You must select a Semester!");
return false;
}
if (course == "") {
window.alert("You must select a Course!");
return false;
}
if (section == "") {
window.alert("You must select a Section!");
return false;
}
var confirmation = window.confirm("Student Name: " + fName + " " + lName + " CWID: " + cwid + " Semester: " + semesterDisplay + " Course: " + course + " Section: " + section + " " + checkDisplay);
if (confirmation) {
window.alert("You have been registered for your course!");
return true;
}
else {
window.alert("Your registration has been canceled.");
return false;
}
}
function resetRegistration() {
var resetForm = confirm("Are you sure you want to reset the form?");
if (resetForm == true)
return true;
return false;
}
/* ]]> */
</script>
</head>
<body>
<!--Heading Element-->
<h1>Greendale Community College</h1>
<center><img src="greendale.jpg" alt="greendale" width="512" height="256" /></center>
<h2 align="center">Course Registration Page</h2>
<form action="FormProcessor.html" name="registration" method="get" onsubmit="return submitRegistration();" onreset="return resetRegistration();">
<h3>Student Information Form</h3>
<!--Student Information-->
First Name:<input type="text" name="firstName"><br>
Last Name:<input type="text" name="lastName"><br>
CWID:<input type="text" name="cwid"><br>
<h3>Semester</h3>
<h4>(choose a semester)</h4>
<!--Radio Buttons to Choose Semester-->
<input type="radio" name="semester" value="fall" /> Fall 2018 <br />
<input type="radio" name="semester" value="spring" /> Spring 2018 <br />
<input type="radio" name="semester" value="summer" /> Summer 2018 <br />
<h3>Courses</h3>
<h4>(choose one course)</h4>
<table>
<!--Drop Down Box for Courses-->
<tr><td style="background:white;border:0">Courses:</td>
<tr>
<td>
<select name="courses" size="1">
<option value=""></option>
<option value="CIS 110">Intro to CIS</option>
<option value="CIS 120">Application Prog I</option>
<option value="CIS 299">System Analysis I</option>
<option value="CIS 330">Web Programming I</option>
<option value="CIS 304">Cobol</option>
</select>
</td>
</tr>
</table>
<h3>Sections</h3>
<h4>(choose one section)</h4>
<table>
<tr><td style="background:white;border:0">Section Numbers:</td>
<tr>
<td>
<select name="section" multiple="multiple" size="5">
<option value="001">CIS 110 001</option>
<option value="gw1">CIS110 GW1</option>
<option value="001">CIS 120 001</option>
<option value="gw1">CIS 120 GW1</option>
<option value="gw1">CIS 302 GW1</option>
<option value="001">CIS 304 001</option>
<option value="gw1">CIS 303 GW1</option>
<option value="001">CIS 321 001</option>
<option value="gw1">CIS 321 GW1</option>
<option value="gw1">CIS 322 GW1</option>
</select>
</td>
</tr>
</table>
<input type="checkbox" name="needForMajor" />
Check if the course is required for your major!<br />
<!--Submit and Reset Buttons Created-->
<input type="submit" name="submit" value="Submit"><br />
<input type="reset" name="reset" value="Reset">
</form>
</body>
</html>

How to perform on-submit form validation

I want to replace the after-submission checks in the form with on-the-fly completeness and correctness checks that are performed when a form field loses focus.
How can I do this?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<title>Form</title>
<style>
body {
width: 500px;
}
.part {
width: 100%;
padding: 5px;
border-bottom: 1px solid #000;
}
label {
margin-right: 5px;
}
.label-left {
text-align: right;
}
.label-right {
text-align: left;
}
.error {
color: #cc0000;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$(document).ready(function() {
function myValidateEMailAddress(email_address) {
var email_pattern = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return email_pattern.test(email_address);
}
function checkPassword(pwd_str) {
var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
return my_pwd_pattern.test(pwd_str);
}
function validatePhoneNumber(phone_number) {
var phone_pattern = /^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/;
return phone_pattern.test(phone_number);
}
$(document).ready(function() {
$('#form').submit(function(e) {
var my_errors = false;
$('.part> .error').remove();
$('#my_submission').empty();
$(':text, :password, textarea').each(function() {
$(this).val($.trim($(this).val()));
if ($(this).val() == '') {
$(this).parent().append('<div class="error">Please provide a value</div>');
my_errors = true;
}
});
if ($('#email').val() != '') {
if (!myValidateEMailAddress($('#email').val())) {
$('#email').parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
}
if ($('#your_password').val() != '') {
if (!checkPassword($('#your_password').val())) {
$('#your_password').parent().append('<div class="error">Please provide a correct password.</div>');
my_errors = true;
}
}
if ($('#phone').val() != '') {
if (!validatePhoneNumber($('#phone').val())) {
$('#phone').parent().append('<div class="error">Please provide a correct phone number.</div>');
my_errors = true;
}
}
if ($('#addresses option:selected').val() == '') {
$('#addresses').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="sex"]:checked').length == 0) {
$(':radio[name="sex"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="subscription"]:checked').length == 0) {
$(':radio[name="subscription"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($('#likes option:selected').val() == '') {
$('#likes').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if (my_errors) {
return false;
}
else {
e.preventDefault();
var my_submission_array = $('#form').serialize().split('&');
if (my_submission_array.length > 0) {
$('#my_submission').html('<h2>Submitted Elements</h2><ul></ul>');
for (var i = 0; i < my_submission_array.length; i++) {
var my_pair = my_submission_array[i].split('=');
$('#my_submission > ul').append('<li>' + my_pair[0] + ': ' + my_pair[1] + '</li>\n');
}
}
}
});
});
// });
</script>
</head>
<body>
<h3>Output:</h3>
<h2>My Questionnaire</h2>
<form name="form" id="form" action="" method="post">
<div class="part">
<label for="addresses" class="label-left">How should you be addressed?</label>
<select name="addresses" id="addresses">
<option value="">Please select one</option>
<option value="first">Mr.</option>
<option value="second">Madam</option>
<option value="third">Miss</option>
<option value="fourth">Dr.</option>
<option value="fifth">Pr.</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Sex:</legend>
<input type="radio" name="sex" id="group1" value="1">
<label for="group1" class="label-right">Male</label>
<input type="radio" name="sex" id="group2" value="2">
<label for="group2" class="label-right">Female</label>
</fieldset>
</div>
<div class="part">
<label for="last_name" class="label-left">Last Name: </label>
<input type="text" name="last_name" id="last_name">
</div>
<div class="part">
<label for="first_name" class="label-left">First Name: </label>
<input type="text" name="first_name" id="first_name">
</div>
<div class="part">
<label for="email" class="label-left">E-Mail: </label>
<input type="text" name="email" id="email">
</div>
<div class="part">
<label for="your_password">Password:</label>
<input type="password" name="your_password" id="your_password" size="10" maxlength="20">
</div>
<div class="part">
<label for="phone" class="label-left">Phone number: </label>
<input type="text" name="phone" id="phone">
</div>
<div class="part">
<label for="likes" class="label-left">What are your likes?</label>
<select name="likes" id="likes">
<option value="">Please select one</option>
<option value="first">Programming</option>
<option value="second"> African literature</option>
<option value="third">Poetry</option>
<option value="four">Dancing</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Do you want to receive our newsletter ?</legend>
<input type="radio" name="subscription" id="group1" value="1">
<label for="group1" class="label-right">Yes</label>
<input type="radio" name="letter" id="group2" value="2">
<label for="group2" class="label-right">No</label>
</fieldset>
</div>
<div class="part">
<label for="comments" class="label-left">Write some comments below:</label>
<textarea name="comments" id="comments" cols="40" rows="3"></textarea>
</div>
<div class="part">
<input type="submit" name="submit" id="submit" value="Submit Form">
</div>
<div id="my_submission"></div>
</form>
</body>
</html>
Before I continue answering, I should note that you're putting jQuery script before <html> tag. This is incorrect. It has to be in <head>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...
performed when a form field loses focus
An element loses focus when you click away from it. jQuery happends to have a blur event for this occasion:
$('input').on('blur', function() {
// your code here
});
So you might want to do it this way:
$('#email').on('blur', function() {
var emailVal = $(this).val();
if (!emailVal || !myValidateEMailAddress(emailVal)) {
$(this).parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
});
the rest of the code might look similar.

Categories