Javascript not executing. No console errors, no validation errors - javascript

When I hit my submit button it just goes straight to the php page. The javascript does not load at all. This is very confusing because I am receiving no errors in console nor when I validate the javascript using external error checkers (such as JShint). The javascript was working at one point in my coding so I have no idea why it stopped working.
JAVASCRIPT:
//jQuery
$(document).ready(function() {
// listen for a click event on any radio element
$('input[type="radio"]').click(function() {
// get the id of the clicked element
var id = $(this).attr('id');
// fade out any existing image elements
$('img').fadeOut(800, function() {
// fade in the image element with the id we're after, with a half second delay (500 milliseconds)
setTimeout(function() {
$('#' + id + 'i').fadeIn(800);
}, 500);
});
});
});
function checkInput() {
var firstName = document.getElementById("fn");
var lastName = document.getElementById("ln");
var email = document.getElementById("email");
var emailR = document.getElementById("emailR");
var postal = document.getElementById("pc");
var city = document.getElementById("city");
var sA = document.getElementById("sA");
var qN = document.getElementById("qty");
var provy = document.getElementById("prov");
var foc = false;
var error = "";
var letters = /^[a-zA-Z]+$/;
var numbers = /^\d+$/;
var letNm = /^(?=.*[a-zA-Z])(?=.*[0-9])/;
//First-Name Validation
if (firstName.value == "" || firstName.value.length > 15 || firstName.value.length < 2 || !firstName.value.match(letters)) {
error += "\n Please enter a valid first name.";
if (foc == false) {
document.getElementById("fn").focus();
foc = true;
}
}
//Last-Name Validation
if (lastName.value == "" || lastName.value.length > 15 || lastName.value.length < 2 || !lastName.value.match(letters)) {
error += "\n Please enter a valid last name";
if (foc == false) {
document.getElementById("ln").focus();
foc = true;
}
}
//street Address
if (sA.value == "" || sA.value.length < 6 || sA.value.length > 30 || !sA.value.match(letNm)) {
error += "\n Please enter a valid street address (must contain letters and numbers, \n and be more than 6 less than 30 chars) ";
if (foc == false) {
document.getElementById("sA").focus();
foc = true;
}
}
//City Validation
if (city.value == "" || city.value.length > 20 || city.value.length < 2 || !city.value.match(letters)) {
error += "\n Please enter a valid city (more than 2 characters, less than 20, all letters)";
if (foc == false) {
document.getElementById("city").focus();
foc = true;
}
}
//Province Validation
var select = provy.options[provy.selectedIndex].value;
if (select == "s") {
error += "\n Please choose a province";
if (foc == false) {
document.getElementsByName("prov").focus();
foc = true;
}
}
//Email Validation
var ei = email.value.lastIndexOf('#');
var dot = email.value.lastIndexOf('.');
if (email.value == "" || email.value.length < 7 || email.value.length > 50 || ei == -1 || dot == -1 || dot < ei + 2) {
error += "\n Please enter a valid email address \n (must have an \"#\" symbol followed by a \".\")";
if (foc == false) {
document.getElementById("email").focus();
foc = true;
}
} else if (emailR.value != email.value) {
error += "\n Your email addresses did not match";
if (foc == false) {
document.getElementById("emailR").focus();
foc = true;
}
}
//Postal Code Validation
var pi = postal.value.lastIndexOf(" ");
var code = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;
if (postal.value == "" || postal.value.length != 7 || !postal.value.match(code) || pi != 3) {
error += "\n Please enter a valid Canadian postal code. E.g. \"N3H 1M1\" ";
if (foc == false) {
document.getElementById("pc").focus();
foc = true;
}
}
//Album selection Validation
var jay = document.getElementsById("jayz");
if (!isOneChecked(jay)) {
error += "\n Please choose an album to purchase";
if (foc == false) {
document.getElementsByName("jayz").focus();
foc = true;
}
}
//quantity validation
if (qN.value == "" || qN.value > 99 || qN.value < 1 || !qN.value.match(numbers)) {
error += "\n Please enter a quantity between 1-99";
if (foc == false) {
document.getElementByName("qntty").focus();
foc = true;
}
}
//error validation:error2 boolean returns either true or false
var error2 = false;
if (foc == false) {
alert("Thank you for signing up!");
error2 = true;
} else {
alert(error);
error2 = false;
}
return error2;
}
//function that trims and converts string to properCase
function properCaseTrim(string) {
var str = string.length;
for (var i = 0; i < str; i++) {
var letter = string.charAt(i);
if (letter == " ") {
string = string.replace(/^\s\s*/, ''); // Remove Preceding white space
string = string.replace(/\s\s*$/, ''); // Remove Trailing white space
}
string = string.charAt(0).toUpperCase() + string.slice(1);
}
return string;
}
function isOneChecked() {
// All <input> tags...
var chx = document.getElementsByTagName('input');
for (var i = 0; i < chx.length; i++) {
// Return true from the function on first match of a checked item
if (chx[i].type == 'radio' && chx[i].checked) {
return true;
}
}
// End of the loop, return false
return false;
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>Assignment #4</title>
<link rel="icon" type="image/x-icon" href="images/favi.ico" />
<link rel="stylesheet" type="text/css" href="styles/main.css"/>
<script type="text/javascript" src="javascript/jquery-1.12.1.js"></script>
<script type ="text/javascript" src="javascript/function.js"></script>
</head>
<body>
<header>
<h1>Jay-Z Albums</h1>
</header>
<fieldset id = "field1">
<legend>Shipping Info</legend>
<p id ="p">All Fields Are Mandatory </p>
<form method = "post" name= "user creation form" onsubmit="return checkInput();" action = "php/validate.php">
First name<br>
<input type="text" name="firstName" id ="fn" onblur="this.value = properCaseTrim(this.value)" value= "" autofocus><br>
Last name<br>
<input type="text" name="lastName" id = "ln" onblur="this.value = properCaseTrim(this.value)" value= ""><br>
Street Address<br>
<input type="text" name="streetAddress" id = "sA" placeholder="123 Main St." onblur="this.value = properCaseTrim(this.value)" value= "" ><br>
<label>
City <br>
<input type="text" name="city" id="city" onblur="this.value = properCaseTrim(this.value)" value= "">
</label>
<br>
Province <br>
<select name ="prov" id ="prov">
<option value = "s">-select-</option>
<option value="Alberta">Alberta</option>
<option value="British Columbia">British Columbia</option>
<option value="Manitoba">Manitoba</option>
<option value="New Brunswick">New Brunswick</option>
<option value="Newfoundland and Labrador">Newfoundland and Labrador</option>
<option value="Nova Scoti">Nova Scotia</option>
<option value="Ontario">Ontario</option>
<option value="Prince Edward Island">Prince Edward Island</option>
<option value="Quebec">Quebec</option>
<option value="Saskatchewan">Saskatchewan</option>
<option value="Northwest Territories">Northwest Territories</option>
<option value="Nunavut">Nunavut</option>
<option value="Yukon">Yukon</option>
</select>
<br>
<label>
Postal Code <br>
<input type="text" name="pc" id="pc" placeholder="A1A 1A1" onblur="this.value = this.value.toUpperCase(); this.value = properCaseTrim(this.value)" value= ""> <br>
</label>
<label>
Email Address<br>
<input type="text" name="email" id="email" value= ""> <br>
</label>
<label>
Repeat Email Address <br>
<input type="text" name="emailR" id="emailR" value= "" > <br>
</label>
<br>
</fieldset>
<fieldset id = "field3">
<legend>Order </legend>
<p> One Album Per Order</p>
<p> Prices shown are without tax </p>
<input type = "radio" name ="jayz" value="rDbt" id= "rD">[1996]Reasonable Doubt-$25 <br>
<input type = "radio" name ="jayz" value="bPrint" id= "bP1">[2001]The Blueprint-$10<br>
<input type = "radio" name ="jayz" value="bPrint2" id = "bP2">[2002]The Blueprint 2-$15<br>
<input type = "radio" name ="jayz" value="kCome" id ="kC">[2006]Kingdom Come-$10<br>
<input type = "radio" name ="jayz" value="bPrint3" id ="bP3">[2009]The Blueprint 3-$25<br>
<input type = "radio" name ="jayz" value="mCarta" id ="mC">[2013]Magna Carta Holy Grail-$30<br>
<div id="q">
# of Albums:
<input type="text" name="quant" id="qty">
</div>
</fieldset>
<aside>
<div id = "divvy">
<img class = "hidden" src="images/rDoubt.jpg" alt="Reasonable Doubt" height="400px" width="400px" id= "rDi">
<img class = "hidden" src="images/bPrint.jpg" alt="the Blueprint" height="400px" width="400px" id= "bP1i">
<img class = "hidden" src="images/bPrint2.jpg" alt="the Blueprint 2" height="400px" width="400px" id = "bP2i">
<img class = "hidden" src="images/kCome.jpg" alt="Kingdom Come" height="400px" width="400px" id ="kCi">
<img class = "hidden" src="images/bPrint3.jpg" alt="the Blueprint 3" height="400px" width="400px" id ="bP3i">
<img class = "hidden" src="images/mCarta.jpg" alt="Magna Carta" height="400px" width="400px" id ="mCi">
</div>
</aside>
<input id="button" type="submit" value="Submit Order" >
</form>
</body>
</html>

Reverse the order of these script tags: (The jquery one should be first)
<script type ="text/javascript" src="javascript/function.js"></script>
<script type="text/javascript" src="javascript/jquery-1.12.1.js"></script>
I suspect your jquery code in function.js is not working due to this issue.

Thats the default behavior of <input type="submit"/>, you have to override it:
$('form').on('submit',function(e){
e.prevetDefault();
//do your JS processing here, call a function and finally make an AJAX request
checkInput();
});
That should do.
On a separate note, I dont think 'name' attribute with spaces is valid. It is best to be kept unique/ or treat as a key or identifier.

Related

Uncaught TypeError: Cannot read property 'checked' of undefined, Checkboxes

I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:
Uncaught TypeError: Cannot read property 'checked' of undefined.
Here is part of the HTML:
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required): <input type="text" name="userName" id="userName" required=""><br> E-Mail (Required): <input type="text" name="mail" id="mail" required=""><br> Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()"><br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other <br>
<textarea></textarea><br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and part of the JavaScript for the checkboxes:
function validChoice()
{
var bookChoice = document.userSurvey.books.value;
var x= "";
for (i=0;i< 4;i++)
{
if (document.userSurvey['bookChoice'+i].checked)
{
bookChoice = document.userSurvey['bookChoice'+i].value;
x = x +"\n"+ bookChoice;
}
}
if (bookChoice == "")
{
window.alert("You must select at least one book category.");
return false;
}
else
{
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
return true;
}
}
I am currently learning in JavaScript therefore I would prefer help in JavaScript only.
Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/
You missed some tag names and missspell them in js function:
<h1>User Survey</h1>
<h2><strong>User Information</strong></h2>
<p>Please enter your details below</p>
<br>
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required):
<input type="text" name="userName" id="userName" required="">
<br> E-Mail (Required):
<input type="text" name="email" id="email" required="">
<br> Phone (Required):
<input type="text" name="phone" id="phone" required="" onchange="validNumber()">
<br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other
<br>
<textarea></textarea>
<br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and js code goes like this:
function validName() {
var name = document.userSurvey.userName.value;
if (!/^[a-zA-Z]*$/g.test(name)) {
alert("Please enter letters a - z only");
document.userSurvey.userName.focus();
return false;
} else {
return true;
}
}
function validNumber() {
var theNumbersOnly = "";
var theChar = "";
var theInput = document.userSurvey.phone.value;
for (i = 0; i < theInput.length; i++) {
theChar = theInput.substring(i, i + 1);
if (theChar >= "0" && theChar <= "9") {
theNumbersOnly = "" + theNumbersOnly + theChar;
}
}
if (theNumbersOnly.length < 10) {
alert("You must enter 10 numbers.");
document.userSurvey.phone.focus();
} else {
var areacode = theNumbersOnly.substring(0, 3);
var exchange = theNumbersOnly.substring(3, 6);
var extension = theNumbersOnly.substring(6, 10);
var newNumber = "(" + areacode + ") ";
newNumber += exchange + "-" + extension;
document.userSurvey.phone.value = newNumber;
return true;
}
}
function validEmail() {
var email = document.userSurvey.email.value;
var atLoc = email.indexOf("#", 1);
var dotLoc = email.indexOf(".", atLoc + 2);
var len = email.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc + 2) {
return true;
} else {
alert("Please enter your e-mail address properly.");
return false;
}
}
function validChoice() {
//var bookChoice = document.userSurvey.books.value;
var bookChoice;
var x = "";
for (var i = 0; i < 4; i++) {
if (document.userSurvey.books[i].checked) {
console.log(document.userSurvey);
bookChoice = document.userSurvey.books[i].value;
x = x + "\n" + bookChoice;
}
}
if (bookChoice == "") {
window.alert("You must select at least one book category.");
return false;
} else {
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
console.log(userName);
console.log(eMail);
console.log(phoneNo);
return true;
}
}
function validAll() {
if ((validName() == true) && (validEmail() == true) && (validNumber() == true) && (validChoice() == true)) {
return true;
} else {
return false;
}
}
You missed email tag name too. regards
You can fix the checkbox issue using the following code. A sensible way to get all the checkboxes in this case is using their shared "name" attribute. There are other ways if your structure was different - e.g. using a CSS class, or adding some other custom attribute to the elements.
function validChoice() {
var bookChoices = "";
var checkboxes = document.getElementsByName("books"); //get all elements named "books" into an array
for (i = 0; i < checkboxes.length; i++) { //loop the array
if (checkboxes[i].checked) { //if the array item at this index is checked, then add it to the list
bookChoices += "\n" + checkboxes[i].value;
}
}
if (bookChoices == "") {
window.alert("You must select at least one book category.");
return false;
} else {
alert(bookChoices); //just for testing
return true;
}
}
See https://jsfiddle.net/7qh5segc/3/ for a demo using the changed validChoice() function.

How to remove class error from select field while validation

Below is a sample code. Whenever i validate i don't want to highlight the select field in red. But just want to show the error beside the select field in Red.
HTML after click submit
<select name="event" class="control-label error">
<option value="">Select</option>
<option value="1">Sample 1</option>
</select>
<label for="event" generated="true" class="error" style="display: inline-block;"><span style="padding:6px; "> Please select something </span></label>
UI
jQuery Validation
$("form").validate({
onkeyup:false,
async: false,
rules: {
event: {
required: true
}
},
messages: {
event: {
required: "<span style='padding:6px; '> Please select Something </span>"
}
}
});
if you are using jquery validate library.. Doc says just add valid class on elements where you don't want the border styling.
hope this will help..
Actually required is Html 5 that should show the error in red color only
while in validation use id to call or validate then use that id in style with your need color
ex
#errorBox1,
#errorBox2,
#errorBox3,
#errorBox4,
#errorBox5,
#errorBox6,
#errorBox7,
#errorBox8,
#errorBox9,
#errorBox10
{
color:blue;
}
This is my external stylesheet
function validate()
{
var status = true;
var a = document.form.Name.value;
var b = document.form.Password.value;
var c = document.form.Cpassword.value;
var d = document.form.Address.value;
var e = document.form.Email.value;
var f = document.form.Mobile.value;
if( a == "" )
{
document.getElementById("errorBox1").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox1").innerHTML = "";
}
if( b == "" )
{
document.getElementById("errorBox2").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox2").innerHTML = "";
}
if( c == "" )
{
document.getElementById("errorBox3").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox3").innerHTML = "";
}
if (b!=c)
{
document.getElementById("errorBox10").innerHTML = "*Password does not match";
status = false;
}
else
{
document.getElementById("errorBox10").innerHTML = "";
}
if( d == "" )
{
document.getElementById("errorBox4").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox4").innerHTML = "";
}
if(e == "" || e.indexOf("#", 0) < 0 || e.indexOf(".", 0) < 0 )
{
document.getElementById("errorBox5").innerHTML = "*Please fill your valid email id ";
status = false;
}
else
{
document.getElementById("errorBox5").innerHTML = "";
}
if(f == "" || f.length !=10 || f.charAt(0)!="9" )
{
document.getElementById("errorBox6").innerHTML = "*Mobile no must be 10 digits";
status = false;
}
else
{
document.getElementById("errorBox6").innerHTML = "";
}
if ((document.form.radio1[0].checked == false) && (document.form.radio1[1].checked == false))
{
document.getElementById("errorBox7").innerHTML = "*Select your Gender";
status = false;
}
else
{
document.getElementById("errorBox7").innerHTML = "";
}
if ((document.form.chk[0].checked == false) && (document.form.chk[1].checked == false))
{
document.getElementById("errorBox8").innerHTML = "*Please fill the checkbox";
status = false;
}
else
{
document.getElementById("errorBox8").innerHTML = "";
}
if (document.form.comment.value == "")
{
document.getElementById("errorBox9").innerHTML = "*Please share your feedback";
status = false;
}
else
{
document.getElementById("errorBox9").innerHTML = "";
}
return status;
}
</script>
</head>
<body>
<div class="rm">
<form name="form" method="post" onsubmit ="return validate();" action=" ">
Name : <input type="text" name="Name" onkeyup="validate();" /><div id="errorBox1"></div>
<br>
Password : <input type="password" name="Password" onkeyup="validate();" /><div id = "errorBox2"></div>
<br>
Confirm Password : <input type="password" name="Cpassword" onkeyup="validate();" /><div id = "errorBox3"></div> <div id = "errorBox10"></div>
<br>
Address : <input type="text" name="Address" onkeyup="validate();" /><div id = "errorBox4"></div>
<br>
Email : <input type="text" name="Email" onkeyup="validate();" /><div id = "errorBox5"></div>
<br>
Mobile No :<input type="text" name="Mobile" onkeyup="validate();" /><div id = "errorBox6"></div>
<br>
Gender : Male<input name="radio1" type="radio" value="Male" onclick="validate();"/>
Female<input name="radio1" type="radio" value="Female" onclick="validate();"/><div id = "errorBox7"></div>
<br>
Computer Courses: <input type="checkbox" name="chk" onclick="validate();" value="Php"/> Php
<input type="checkbox" name="chk" onclick="validate();" value="ccna"/> Ccna <div id = "errorBox8"></div>
<br>
CommentBox : <textarea cols = "25" name= "comment" onkeyup="validate();" /></textarea><div id = "errorBox9"></div>
<br>
<div class="submit">
<input type="submit" name="submit" value="Submit" >
<input type="reset" value="Reset"></submit>
Thanks everyone for the response. I just did the following in validate part. I just added a Highlight and it worked. I seriously don't know how it worked. But thanks to Sathvik Cheela for giving an idea about highlight and unhighlight.
$("form").validate({
onkeyup:false,
async: false,
rules: {
event: {
required: true
}
},
messages: {
event: {
required: "<span style='padding:6px; '> Please select Something </span>"
}
},
highlight: function(element, errorClass) {
}
});
UI (Now)

how to hide errorbox validation in java script

This code below is working but I want some modification in this code.
When user is not filling the box it is displaying error box that part is working but after filling it should disappear. So please anyone help me to solve the issue.
I have post the code here including html and java script so just copy and run it it will work and try to resolve my issue.
<html>
<head>
<script type="text/javascript">
function validate()
{
var fname = document.form.Name.value;
var lname = document.form.Lame.value;
var same = document.form.Same.value;
if( fname == "" )
{
document.form.Name.focus() ;
document.getElementById("errorBox1").innerHTML = "enter the first name";
return false;
}
if( lname == "" )
{
document.form.Lame.focus() ;
document.getElementById("errorBox2").innerHTML = "enter the last name";
return false;
}
if( same == "" )
{
document.form.Same.focus() ;
document.getElementById("errorBox3").innerHTML = "enter the Same name";
return false;
}
}
</script>
</head>
<body>
<form name="form" >
SSS :<input type="text" name="Name" value="" class="input_name" ><div id="errorBox1"> </div>
<br>
SSmjhjk :<input type="text" name="Lame" value="" class="input_name" ><div id = "errorBox2"></div>
<br>
nngb :<input type="text" name="Same" value="" class="input_name" ><div id = "errorBox3"></div>
<input type=button onClick="validate()" value=check>
</form>
In my first notice, You have the syntax error in your script. In your last condition you have written the code like if else if( same == "" ). This is wrong.
If you want check and display error for all the textbox at the same time, then you need to remove the return property from the script. Update your script like below.
function validate()
{
var fname = document.form.Name.value;
var lname = document.form.Lame.value;
var same = document.form.Same.value;
document.getElementById("errorBox1").innerHTML ="";
document.getElementById("errorBox2").innerHTML ="";
document.getElementById("errorBox3").innerHTML ="";
if( fname == "" )
{
document.getElementById("errorBox1").innerHTML = "enter the first name";
}
if( lname == "" )
{
document.getElementById("errorBox2").innerHTML = "enter the last name";
}
if( same == "" )
{
document.getElementById("errorBox3").innerHTML = "enter the Same name";
}
}
HTML
<form name="form" >
SSS :<input type="text" name="Name" value="" class="input_name" onkeyup="validate();" /><div id="errorBox1"> </div>
<br>
SSmjhjk :<input type="text" name="Lame" onkeyup="validate();" value="" class="input_name" /><div id = "errorBox2"></div>
<br>
nngb :<input type="text" name="Same" onkeyup="validate();" value="" class="input_name" /><div id = "errorBox3"></div>
<input type="button" onclick="validate();" value="check" />
</form>
Fiddle Demo
Try this , this might work for you
function validate() {
var fname = document.form.Name.value;
var lname = document.form.Lame.value;
var same = document.form.Same.value;
if (fname == "") {
document.form.Name.focus();
document.getElementById("errorBox1").innerHTML = "enter the first name";
return false;
} else {
document.getElementById("errorBox1").innerHTML = "";
}
if (lname == "") {
document.form.Lame.focus();
document.getElementById("errorBox2").innerHTML = "enter the last name";
return false;
} else {
document.getElementById("errorBox2").innerHTML = "";
}
if (same == ""){
document.form.Same.focus();
document.getElementById("errorBox3").innerHTML = "enter the Same name";
return false;
} else {
document.getElementById("errorBox3").innerHTML = "";
}
}
use input type like this
<input type="text" id="fname" onkeyup="validate()">
This will help you
If you want to use javascript only, you can hide the error div:
document.getElementById("errorBox1").style.display = 'none';

Focus function in JavaScript

HTML Code:
<html>
<head>
<title>Registration</title>
<meta charset="utf-8">
<link href="home.css" rel="stylesheet" type="text/css"/>
<link href="booking.css" rel="stylesheet" type="text/css"/>
<script src="val_registration.js" type="text/javascript"></script>
<link rel="stylesheet" href="jquery.css">
<script src="jquery01.js" type="text/javascript"></script>
<script src="jquery02.js" type="text/javascript"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<script language="JavaScript1.2">
var howOften = 5; //number often in seconds to rotate
var current = 0; //start the counter at 0
var ns6 = document.getElementById&&!document.all; //detect netscape 6
// place your images, text, etc in the array elements here
var items = new Array();
items[0]="<a href='link.htm'><img alt='photo01' src='photo01.jpg' height='237' width='750' border-style='inset' border-weight:'10px' /></a>"; //a linked image
items[1]="<a href='link.htm'><img alt='photo02' src='photo02.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
items[2]="<a href='link.htm'><img alt='photo03' src='photo03.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
items[3]="<a href='link.htm'><img alt='photo04' src='photo04.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
items[4]="<a href='link.htm'><img alt='photo05' src='photo05.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
function rotater() {
document.getElementById("placeholder").innerHTML = items[current];
current = (current==items.length-1) ? 0 : current + 1;
setTimeout("rotater()",howOften*1000);
}
function rotater() {
if(document.layers) {
document.placeholderlayer.document.write(items[current]);
document.placeholderlayer.document.close();
}
if(ns6)document.getElementById("placeholderdiv").innerHTML=items[current]
if(document.all)
placeholderdiv.innerHTML=items[current];
current = (current==items.length-1) ? 0 : current + 1; //increment or reset
setTimeout("rotater()",howOften*1000);
}
window.onload=rotater;
</script>
</head>
<body>
<div id="login" name="login">
&nbsp Login&nbsp&nbsp<b><b>|</b></b>
&nbspNew user?&nbsp&nbsp
</div>
<img src="logo.jpg" alt="logo" id="logo" width="500" height="100" usemap="#logomap"/></br>
<map id="logomap" name="logomap">
<area shape="rect" coords="0,0,743,146" href="home.htm" alt="home"/>
<area shape="default" coords"0,0,743,146" href="home.htm" alt="home"/>
</map></br>
<div id="placeholderdiv"></div><br/>
<div id="mlink" >
Home
About Us
Promotion
Contact Us
FAQs
</div><br/>
<div id="opac">
<h1> Registration </h1>
<hr/>
<form action="success(registration_page).html" method="post" id="myform" onsubmit="return val_registration ()">
<table rules="none" cellpadding="10px" cellspacing="10px">
<tr>
<td><label for="Username">Username(No case sensitive):<span id="imp">*</span></label></td><td><input type="text" id="Username" tabindex="1"/>
<br/><span class="eg"> eg:ZerOGravitY</span></td>
</tr>
<tr>
<td><label for="Password">Password(Must more than<br/> 8 characters):<span id="imp">*</span></label></td><td><input type="text" id="Password" tabindex="2"/>
<br/><span class="eg"> eg:567834gravity</span></td></td>
</tr>
<tr>
<td><label for="Retype_password">Retype password:<span id="imp">*</span></label></td><td><input type="text" id="Retype_password" tabindex="3"/>
<br/><span class="eg"> eg:567834gravity</span></td></td>
</tr>
<tr>
<td><label for="First_name">First name:<span id="imp">*</span></label></td><td><input type="text" id="First_name" tabindex="4"/>
<br/><span class="eg"> eg:Loh</span></td></td>
</tr>
<tr>
<td><label for="Last_name">Last name:<span id="imp">*</span></label></td><td><input type="text" id="Last_name" tabindex="5"/>
<br/><span class="eg"> eg:Le You</span></td></td>
</tr>
<tr>
<td><label for="ID_number">ID number (Please omit '-') :<span id="imp">*</span></label></td><td><input type="text" id="ID_number" maxlength="12" tabindex="6"/>
<br/><span class="eg"> eg:940731140991</span></td></td>
</tr>
<tr>
<td><label for="datepicker">DOB:<span id="imp">*</span></label></td>
<td><input type="text" id="datepicker" tabindex="7"/></td>
</tr>
<tr>
<td>Mobile number:<span id="imp">*</span></td>
<td colspan="3">
<select tabindex="8">
<optgroup label="Prefix">
<option value="010">010</option>
<option value="012">012</option>
<option value="013">013</option>
<option value="016">016</option>
<option value="017">017</option>
<option value="018">018</option>
<option value="019">019</option>
</optgroup>
</select>
<input type="text" id="Mobile_number" tabindex="9"/>
<input type="text" class="err" id="err_Mobile_number" readonly="readonly"/>
<br/><span class="eg">
eg:2345678 or 23456789</span>
</td>
</tr>
<tr>
<td><label for="E_mail">E-mail:<span id="imp">*</span></label></td>
<td><input type="text" id="E_mail" tabindex="10"/>
<br/><span class="eg"> eg:abc123#hotmail.com</span></td></td>
</tr>
<tr>
<td colspan="4"><input type="submit" value="Confirm" id="confirm2" tabindex="11" />
<input type="reset" value="Cancel" id="cancel2" tabindex="12"/></td>
</tr>
<tr>
<td>Notes: <span id="imp">*</span> indicates the column that must be filled</td>
</tr>
</table>
</form>
</div>
<hr/>
<b><i id="copyright">Copyrighted : © 2014 I ♥ Travels agency. </i></b>
<b><address id="address"> Address : I love agency, Taman Setapak, Jalan Genting Klang, 53300 Kuala Lumpur </address></b>
</body>
</html>
This is my JavaScript code (for form validation):
function val_registration ()
{
var val_Username = document.getElementById("Username").value;
var string_Username = /^[a-zA-Z0-9]{1,}$/;
var err = "";
if (val_Username == null || val_Username == "" || !string_Username.test(val_Username))
{
err += "\u2022Username cannot be blank/Username can contain\n alphabets or numbers only.\n";
document.getElementById("Username").focus();
}
var val_Password = document.getElementById("Password").value;
var string_Password = /^[a-zA-Z0-9]{9,}$/;
if (val_Password == null || val_Password == "" || !string_Password.test(val_Password))
{
err += "\u2022Password cannot be blank/Password can contain\n alphabets or numbers only and it must contain at \n least 9 characters.\n";
document.getElementById("Password").focus();
}
var val_Retype_password = document.getElementById("Retype_password").value;
if (val_Retype_password == null || val_Retype_password == "" || val_Retype_password != val_Password)
{
err += "\u2022Retype password cannot be blank/Retype password\n must same with password typed.\n";
document.getElementById("Retype_password").focus();
}
var val_First_name = document.getElementById("First_name").value;
var string_First_name = /^[a-zA-Z]{1,}$/;
if (val_First_name == null || val_First_name == "" || !string_First_name.test(val_First_name))
{
err += "\u2022Firstname cannot be blank/Firstname can contain \u00A0alphabets only.\n";
document.getElementById("First_name").focus();
}
var val_Last_name = document.getElementById("Last_name").value;
var string_Last_name = /^[ a-zA-Z#'\-_()\.,]{1,}$/;
if (val_Last_name == null || val_Last_name == "" || !string_Last_name.test(val_Last_name))
{
err += "\u2022Lastname cannot be blank/Lastname can contain\n alphabets or special symbols(# ' - _ ( ).,) only.\n";
document.getElementById("Last_name").focus();
}
var val_ID_number = document.getElementById("ID_number").value;
var string_ID_number = /^[0-9]{12}$/;
if (val_ID_number == null || val_ID_number == "" || !string_ID_number.test(val_ID_number))
{
err += "\u2022Id number cannot be blank/Id number can contain\n excatly 12 numbers only.\n";
document.getElementById("ID_number").focus();
}
var val_datepicker = document.getElementById("datepicker").value;
if (val_datepicker == null || val_datepicker == "")
{
err += "\u2022DOB cannot be blank.\n";
document.getElementById("datepicker").focus();
}
var val_Mobile_number = document.getElementById("Mobile_number").value;
var string_Mobile_number = /^[0-9]{7,8}$/;
if (val_Mobile_number == null || val_Mobile_number == "" || !string_Mobile_number.test(val_Mobile_number))
{
err += "\u2022Mobile number cannot be blank/Mobile number can\n \u00A0contain 7 or 8 numbers only.\n";
document.getElementById("Mobile_number").focus();
}
var val_E_mail = document.getElementById("E_mail").value;
var atpos = val_E_mail.indexOf("#");
var dotpos = val_E_mail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2 >= val_E_mail.length)
{
err += "\u2022E-mail cannot be blank/E-mail format must follow\n \u00A0the example provided.\n";
document.getElementById("E_mail").focus();
}
if (err != null || err != "")
{
alert(err);
return false;
}
}
This works fine except for one thing:
When all fields are empty, an alert box pops up to indicate the error. However, after I click 'OK', it directly moves to the DOB field instead of
the username field.
When I click OK, I want it to validate and focus on the first element in the sequence which is not filled or is invalid.
For example: If both the username and password fields are empty and I click OK, the focus should go to the username field first.
you need to return false; after each validation check!
try this:
Edit1:
function val_registration()
{
var $invalidInput;
var val_Username = document.getElementById("Username").value;
var string_Username = /^[a-zA-Z0-9]{1,}$/;
var err = "";
if (val_Username == null || val_Username == "" || !string_Username.test(val_Username))
{
err += "\u2022Username cannot be blank/Username can contain\n alphabets or numbers only.\n";
var $input = document.getElementById("Username");
$invalidInput=$input;
}
var val_Password = document.getElementById("Password").value;
var string_Password = /^[a-zA-Z0-9]{9,}$/;
if (val_Password == null || val_Password == "" || !string_Password.test(val_Password))
{
err += "\u2022Password cannot be blank/Password can contain\n alphabets or numbers only and it must contain at \n least 9 characters.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Password");
$invalidInput=$input;
}
}
var val_Retype_password = document.getElementById("Retype_password").value;
if (val_Retype_password == null || val_Retype_password == "" || val_Retype_password != val_Password)
{
err += "\u2022Retype password cannot be blank/Retype password\n must same with password typed.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Retype_password");
$invalidInput=$input;
}
}
var val_First_name = document.getElementById("First_name").value;
var string_First_name = /^[a-zA-Z]{1,}$/;
if (val_First_name == null || val_First_name == "" || !string_First_name.test(val_First_name))
{
err += "\u2022Firstname cannot be blank/Firstname can contain \u00A0alphabets only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("First_name");
$invalidInput=$input;
}
}
var val_Last_name = document.getElementById("Last_name").value;
var string_Last_name = /^[ a-zA-Z#'\-_()\.,]{1,}$/;
if (val_Last_name == null || val_Last_name == "" || !string_Last_name.test(val_Last_name))
{
err += "\u2022Lastname cannot be blank/Lastname can contain\n alphabets or special symbols(# ' - _ ( ).,) only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Last_name");
$invalidInput=$input;
}
}
var val_ID_number = document.getElementById("ID_number").value;
var string_ID_number = /^[0-9]{12}$/;
if (val_ID_number == null || val_ID_number == "" || !string_ID_number.test(val_ID_number))
{
err += "\u2022Id number cannot be blank/Id number can contain\n excatly 12 numbers only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("ID_number");
$invalidInput=$input;
}
}
var val_datepicker = document.getElementById("datepicker").value;
if (val_datepicker == null || val_datepicker == "")
{
err += "\u2022DOB cannot be blank.\n";
if($invalidInput==undefined){
var $input = document.getElementById("datepicker");
$invalidInput=$input;
}
}
var val_Mobile_number = document.getElementById("Mobile_number").value;
var string_Mobile_number = /^[0-9]{7,8}$/;
if (val_Mobile_number == null || val_Mobile_number == "" || !string_Mobile_number.test(val_Mobile_number))
{
err += "\u2022Mobile number cannot be blank/Mobile number can\n \u00A0contain 7 or 8 numbers only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Mobile_number");
$invalidInput=$input;
}
}
var val_E_mail = document.getElementById("E_mail").value;
var atpos = val_E_mail.indexOf("#");
var dotpos = val_E_mail.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= val_E_mail.length)
{
err += "\u2022E-mail cannot be blank/E-mail format must follow\n \u00A0the example provided.\n";
if($invalidInput==undefined){
var $input = document.getElementById("E_mail");
$invalidInput=$input;
}
}
if (err != null || err != "")
{
$invalidInput.focus();
alert(err);
return false;
}
}
Why it was not working before:
your script was checking each element setting focus and adding error message as required for each element till the last element in the list. Focus state can only be active for a single element on the page at a time. Since the last erroneous element was receiving the focus every time for all the elements, it never stopped at first element.
What I did:
In updated script: I took a variable to store invalid element's reference. As soon the code finds an invalid element- it assigns it to variable $invalidElement. It does the same for every element. So this way $invalidElement always refere to first erroneous element at a time whereas errors get added to the error list every time.
In the end it checks if error is not null. It it is, focus to the first erroneous element and show the error message.
Simple as that!
Hope it helps!
Usually on HTML, the focus order of elements depends on tabindex attribute.
However, if you want to avoid the "natural" or the defined by tabindex order of your focusing, you can always use
yourObject.focus();
Just define the situation you want to control and the behaviour you need to apply when it happens.

How to get the select part to send with email

I have made up a form for my cousin that's going to be using it for her class sign ups at her job. What the code does is when you select a option from the first box the second box displays the day, date, and time. I got it working from a recent post I found on here. My problem is that it doesn't show up in a email after someone has submit it. How can I get it to function so it can get send and show up in a email.
Form example http://crl.x10.mx/rosie_class_form.html
This is what I get in my email...
Message sent on: Saturday, December 22, 2012
Name:John Doe
Email:yours#email.com
Phone:222-222-2222
Class & Time: <-- is part not showing up
Comment:
I'll see you there
Everything gets send but the Class & Time part.
html code: (code between the body) choice_1 = Class and choice_2 = Time
Name <input type="text" id="full_name" name="full_name" value="full_name" onBlur="if(this.value == ''){ this.value = 'full_name'; this.style.color = '#BBB';}" onFocus="if(this.value == 'full_name'){ this.value = ''; this.style.color = '#000';}" style="color:#BBB;" /><br /><br />
Phone <input type="text" id="phone" name="phone" value="xxx-xxx-xxxx" onBlur="if(this.value == ''){ this.value = 'xxx-xxx-xxxx'; this.style.color = '#BBB';}" onFocus="if(this.value == 'xxx-xxx-xxxx'){ this.value = ''; this.style.color = '#000';}" style="color:#BBB;"/><br /><br />
Email <input type="email" id="email" name="email" value="example#domain.com" onBlur="if(this.value == ''){ this.value = 'example#domain.com'; this.style.color = '#BBB';}" onFocus="if(this.value == 'example#domain.com'){ this.value = ''; this.style.color = '#000';}" style="color:#BBB;" /><br /><br />
Select your class and time.
<br />
<select name="choice_1" id="choice_1" onChange="choice_1(this.'choice_1');">
<option value="0" selected="selected">Class...</option>
<option value="1">Beginners Cake</option>
<option value="2">Basic Cake</option>
<option value="3">Cake</option>
<option value="4">Candy</option>
<option value="5">Cookie</option>
<option value="6">Sugar Cookie</option>
<option value="7">CupCake</option>
<option value="8">Flower</option>
<option value="9">Fondant</option>
<option value="10">Gum paste</option>
</select>
<br />
<select name="choice_2" id="choice_2" onChange="choice_2(this.'choice_2');">
<option value="0" selected="selected">Time...</option>
<option value="1">Monday 01/07/13 6:30 to 10:30pm</option>
<option value="2">Wednesday 01/09/13 5:30 to 7:45pm</option>
<option value="2">Wednesday 01/09/13 10:00 to 12:00am</option>
<option value="3">12</option>
<option value="4">11</option>
<option value="5">13</option>
<option value="6">10</option>
<option value="7">9</option>
<option value="8">7</option>
<option value="9">5</option>
<option value="10">4</option>
</select>
<input type="hidden" name="choice_1" id="choice_1" value=""/>
<input type="hidden" name="choice_2" id="choice_2" value=""/>
<br /><br />
Comments (<span class="optional">Optional</span>) <br />
<textarea name="message" id="message" rows="10" cols="40"></textarea>
<br /><br />
<strong>Please add these numbers:</strong>
<span id="digit1"></span> +
<span id="digit2"></span> =
<input type="text" id="answer" size="2">
<br />
<div id="status"><button type="button" id="myBtn" onClick="ajax_postContact();">Send Now</button></div>
class_signups.js (random js name)
function s () {
var choice_1 = document.getElementsByName("choice_1");
for ( var i = 0; i < choice_1.length; i++ ) {
if ( choice_1[i].checked ){
var val = choice_1[i].value;
return val;
}
}
}
function ajax_postContact(){
var msg = document.getElementById("message").value;
var answer = document.getElementById("answer").value;
var fn = document.getElementById("full_name").value;
var ph = document.getElementById("phone").value;
var em = document.getElementById("email").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
///// error checking ////
var sum = digit1 + digit2;
if(answer == null || answer == ""){
alert("Please add the numbers");
return false;
}
else if(answer != sum){
alert("Your answer to the math problem is wrong. Please try again.");
return false;
}
else if(fn == null || fn == ""){
alert("Please type your name");
return false;
}
else if(em == null || em == ""){
alert("Please type your email address");
return false;
}
else if(msg == null || msg == ""){
alert("Please leave a message");
return false;
}
else{
var hr = new XMLHttpRequest();
var url = "signups.php";
var vars = "full_name="+fn+"&phone="+ph+"&email="+em+"&choice_1="+s()+"&message="+msg;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "<img src='images/loaderblue.gif' alt='Loader'>";
document.getElementById("full_name").value = "";
document.getElementById("phone").value = "";
document.getElementById("email").value = "";
document.getElementById("message").value = "";
document.getElementById("answer").value = "";
}
}
choice1&2.js (goes with the select part)
$(document).ready(function(){
$("#choice_1").change(function() {
if($(this).data('options') == undefined){
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options',$('#choice_2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#choice_2').html(options);
});
});

Categories

Resources