Focus function in JavaScript - 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.

Related

how to insert current row field value into next row field value dynamically in an html table table

I have a scenario where I need to get year from previous row of the table.
For example,
Row 1 has From year and to year ( user inserts ).
Row 2 should get from year value from row 1 and to year will be entered by user.
Row 3 From year(To year from row 2) and To year( Entered by User).
Note: If To year is 9999, then it shouldn't allow user to enter next row values and from year is Previous row to year +1.
Row 2 From year = Row 1 To year +1
Row 3 From year = Row 2 To year +1
currently, from year is not incrementing from previous row and not auto populating.
Please help me
Thanks
'''
<head>
<script>
var max = 5;
var min = 1;
function yearValidation(lineNum)
{
if(lineNum <= max && lineNum >=min)
{
var toYearVal = document.getElementById("to_year"+lineNum).value;
var fromYearVal = document.getElementById("from_year"+lineNum).value;
if(lineNum != max && !isNaN(toYearVal) && !isNaN(fromYearVal) && toYearVal.length == 4)
{
toYearVal = parseInt(toYearVal);
fromYearVal = parseInt(fromYearVal);
if(fromYearVal >= toYearVal)
{
alert("To year "+toYearVal+" value is greater than from year : "+fromYearVal)
document.getElementById("to_year"+lineNum).value = "";
}
else
{
if(toYearVal<9999 && toYearVal>=1000)
{
toYearVal = toYearVal + 1;
document.getElementById("from_year"+(lineNum+1)).value = toYearVal;
lineNum = lineNum + 1;
for(i=lineNum;i<=max;i++)
{
document.getElementById("from_year"+(i+1)).value = "";
document.getElementById("to_year"+(i+1)).value = "";
document.getElementById("to_year"+(i+1)).readOnly = false;
}
}
else if(toYearVal == 9999)
{
lineNum = lineNum + 1;
for(i=lineNum;i<=max;i++)
{
document.getElementById("from_year"+i).value = "";
document.getElementById("to_year"+i).value = "";
//document.getElementById("to_year"+i).readOnly = true;
}
}
}
}
}
}
function validate(evt) {
var theEvent = evt || window.event;
// Handle paste
if (theEvent.type === 'paste') {
key = event.clipboardData.getData('text/plain');
} else {
// Handle key press
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
}
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>
</head>
<td width="350" align="left" valign="middle">
<c:if>
A. TEMP 01(From <input id="TEMPFromYr" name="TEMPFromYr" style="width: 32px;" class="no-outline" type="text" maxlength="4" onkeypress='validate(event)' /> & <input id="TEMPToYr1" name="TEMPToYr" size="4" type="text" maxlength="4" onkeyup="yearValidation()" onkeypress='validate(event)' /> )
</c:if>
<c:if>
B. TEMP 02(From <input id="TEMPFromYr" name="TEMPFromYr" style="width: 32px;" class="no-outline" type="text" maxlength="4" onkeypress='validate(event)' /> & <input id="TEMPToYr" name="TEMPToYr" size="4" type="text" maxlength="4" onkeyup="yearValidation()" onkeypress='validate(event)' /> )
</c:if>
<c:if}">
C. TEMP 03(From <input id="TEMPFromYr" name="TEMPFromYr" style="width: 32px;" class="no-outline" type="text" maxlength="4" onkeypress='validate(event)' /> & <input id="TEMPToYr" name="TEMPToYr" size="4" type="text" maxlength="4" onkeyup="yearValidation()" onkeypress='validate(event)' /> )
</c:if>
</td>
'''

Java Script Functions Don't work and How do i add my javascript file to html and get it to work

I have my javascript file and code done, called script.js and I've added it to my HTML file. I'm very new to this and I'm not sure if I'm doing it right. the functions don't seem to work either. I am very lost and would just like yo figure it out. thank you.
this is my javascript file called (script.js)
$(document).ready(function () {
//When add database, will pull total from database
var total = 30;
var totalTax = total * 0.8;
var totalShip = total * 0.3;
var totalAll = total + totalTax + totalShip;
document.getElementById("totalShop").innerHTML = total;
document.getElementById("totalTax").innerHTML = totalTax;
document.getElementById("shipping").innerHTML = totalShip;
document.getElementById("totalDue").innerHTML = totalAll;
});
function applyActiveCss(id) {
for (var i = 0; i < document.links.length; i++) {
if (document.links[i].id == id) {
document.links[i].className = 'active';
}
else {
document.links[i].className = 'links';
}
}
}
function validateCheckout() {
if (document.checkoutForm.cardNumber.value == "") {
alert("Please provide card number");
document.checkoutForm.cardNumber.focus();
return false;
}
if (document.checkoutForm.month.value == "" || isNaN(document.checkoutForm.month.value) ||
document.checkoutForm.month.value.length != 2) {
alert("Please provide your month");
document.checkoutForm.month.focus();
return false;
}
if (document.checkoutForm.year.value == "" || isNaN(document.checkoutForm.year.value) ||
document.checkoutForm.year.value.length != 4) {
alert("Please provide your month");
document.checkoutForm.year.focus();
return false;
}
return (true);
}
function validateUserInfo() {
if (document.userInfo.fullname.value == "") {
alert("Please provide full name");
document.checkoutForm.cardNumber.focus();
return false;
}
if (document.userInfo.email.value == "") {
alert("Please provide your Email!");
document.userInfo.email.focus();
return false;
}
var emailID = document.userInfo.email.value;
var atpos = emailID.indexOf("#");
var dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter correct email ID")
document.userInfo.email.focus();
return false;
}
if (document.userInfo.zipcode.value == "" ||
isNaN(document.userInfo.zipcode.value) ||
document.userInfo.zipcode.value.length != 5) {
alert("Please provide a zip in the format 12345");
document.userInfo.zipcode.focus();
return false;
}
var phoneID = document.userInfo.phone.value;
var dashpos1 = phoneID.indexOf("-");
var dashpos2 = phoneID.lastIndexOf("-");
for (var i = 3; i < 7; i++) {
phoneID[i] = phoneID[i + 1];
}
for (var j = 6; j < 8; j++) {
phoneID[j] = phoneID[j + 2];
}
if (document.userInfo.phone.value == "" ||
document.userInfo.phone.value.length != 12
|| dashpos1 != 3 || dashpos2 != 7 || isNaN(phoneID)) {
alert("Please provide a phone number in the format 123-456-7890");
document.userInfo.phone.focus();
return false;
}
return (true);
}
and this is part of my HTML file called (userinfo.html)
¿<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Personal Information</title>
<link rel="stylesheet" type="text/css" href="StyleSheet1.css">
</head>
<body>
<script src="script.js"> </script>
<h1>User Information</h1>
<p>Please fill out the following information.</p>
<!--<form class="" action="submit.php" method="post">-->
<form action=".shipinfo.html" name="userInfo" onsubmit="return (validateUserInfo());">
<table>
<tbody>
<tr>
<td>
Full Name: <br>
<input type="text" maxlength="100" name="fullname" required>
</td>
<td>
Phone Number: <br>
<input type="number" minlength = "12" maxlength="12" name="phone"
placeholder="123-456-7890">
</td>
</tr>
<tr>
<td>
Address Line 1: <br>
<input type="text" maxlength="100" name="add1" required>
</td>
<td>
Address Line 2: <br>
<input type="text" maxlength="100" name="add2">
</td>
</tr>
<tr>
<td>
City: <br>
<input type="text" maxlength="100" name="city" required>
</td>
I dont see the following jquery script in your file (so it does not read the document ready part and you do not see the 'document loaded' in your console.
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
Another error you are getting in the console is 'Cannot read property 'innerHTML' of null' for this:
document.getElementById("totalShip").innerHTML = total;
This happens when the element, in this case 'totalship', is not accessible or available in your webpage and as such its property cannot be read. Since you are accessing an id, can you provide your css file here?
In addition, where is the access to your database through these files (.userInfo, .checkoutForm etc.) are not accessible via your files as of now.

Javascript not executing. No console errors, no validation errors

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.

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';

Javascript Validation for a Complex Password [duplicate]

This question already has answers here:
Password Strength Meter [closed]
(3 answers)
Closed 9 years ago.
I'm creating a Create Account page and I'm trying to verify that the password they are creating follows the proper format.
The password format needs to be:
Minimum of:
15 characters
2 UPPER
2 lower
2 Numbers
2 Special
I've searched and have only been able to find a validation script that checks for 1 of each character, which I am currently using. I'm also using a function to confirm the password and confrim password fields match on key up, and a separate function to do the same on submit. Validating that they match on submit is not working either.
Here's what I have so far:
<script>
var anUpperCase = /[A-Z]/;
var aLowerCase = /[a-z]/;
var aNumber = /[0-9]/;
var aSpecial = /[!|#|#|$|%|^|&|*|(|)|-|_]/;
function testpasswd(form, ctrl, value)
{
if (value.length < 15 || value.search(anUpperCase) == -1 ||
value.search (aLowerCase) == -1 || value.search (aNumber) == -1 || value.search (aSpecial) == -1)
{
document.getElementById("pw").innerHTML="Invalid Password";
}
else
{
location.href = "submit.cfm";
}
}
function checkpasswds()
{
theForm = document.getElementById ( 'reg' ) ;
confm = document.getElementById ( 'confirm') ;
if (theForm.passwd2.value != '' && theForm.passwd1.value != '')
{
if (theForm.passwd1.value != theForm.passwd2.value)
{
confm.style.background = "url('images/wrong.png')" ;
confm.style.backgroundRepeat = "no-repeat" ;
confm.style.backgroundPosition = "right" ;
}
else
{
confm.style.background = "url('images/correct.png')" ;
confm.style.backgroundRepeat = "no-repeat" ;
confm.style.backgroundPosition = "right" ;
}
}
}
function cnfmpasswd(form, ctrl, value)
{
theForm = document.getElementById ( 'reg') ;
if (theForm.passwd2.value != '' && theForm.passwd1.value != '')
{
if (theForm.passwd1.value != theForm.passwd2.value)
{
return (false);
}
else
{
return (true);
}
}
}
function submitForm()
{
document.forms['reg'].submit;
testpasswd('reg','passwd1',document.getElementById('passwd1').value);
cnfmpasswd('reg','passwd2',document.getElementById('passwd2').value);
}
</script>
<cfform action="submit.cfm" method="post" name="reg" id="reg" format="html">
<table width="947" border="0">
<tr>
<td width="180" align="right"><p style="color:#EB0000; font-size:14px" align="center" id="pw"></p></td>
<td width="118" align="right">
Password:
</td>
<td width="635">
<cfinput
name="passwd1"
title="Must contain at least 2 of each of the following: UPPERCASE, lowercase, numeric, and special characters"
type="password"
required="yes"
onKeyUp="checkpasswds();"
/>
(min 15 characters with 2 UPPER, 2 lower, 2 numeric, and 2 special)
</td>
</tr>
<tr>
<td id="confirm" align="right"></td>
<td align="right">
Confirm Password:
</td>
<td>
<cfinput
name="passwd2"
type="password"
required="yes"
onKeyUp="checkpasswds();"
/>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>
<cfinput name="submit"
type="button"
value="Submit"
class="button"
onClick="submitForm()"
/>
</td>
</tr>
</table>
I'm a little new with javascript. Details will be greatly appreciated. I hope someone can help! Thanks!
I'm not looking for a strength meter or on keyup validation. I simply want to validate the password on submit.
This should do it:
var password = "TEstpass1aaaaaaa$$";
console.log(isOkPass(password));
function isOkPass(p){
var anUpperCase = /[A-Z]/;
var aLowerCase = /[a-z]/;
var aNumber = /[0-9]/;
var aSpecial = /[!|#|#|$|%|^|&|*|(|)|-|_]/;
var obj = {};
obj.result = true;
if(p.length < 15){
obj.result=false;
obj.error="Not long enough!"
return obj;
}
var numUpper = 0;
var numLower = 0;
var numNums = 0;
var numSpecials = 0;
for(var i=0; i<p.length; i++){
if(anUpperCase.test(p[i]))
numUpper++;
else if(aLowerCase.test(p[i]))
numLower++;
else if(aNumber.test(p[i]))
numNums++;
else if(aSpecial.test(p[i]))
numSpecials++;
}
if(numUpper < 2 || numLower < 2 || numNums < 2 || numSpecials <2){
obj.result=false;
obj.error="Wrong Format!";
return obj;
}
return obj;
}

Categories

Resources