I am currently working on some homework for school and I am little stuck with my switch!
I am getting a response up until alert(card) in checkcard();
my problem is, none of the cases will actually validate the type of card that is is in reference too, I am not allowed to use any addons like jQuery etc etc.
I'll post relevant code and be glad to hear from you guys :D I've commented the lines with #### for ease. Also, getcard does return correct card type as wished.
function getCard(){
var cardType = "unknown";
var cardTypeArray = document.getElementById("chooseCard").getElementsByTagName("input");
for(var i = 0; i < cardTypeArray.length; i++){
if (cardTypeArray[i].checked) {
cardType = cardTypeArray[i].value;
}
}
alert ("cardtype is" + cardType);
return cardType;
}
function checkCard(cardNumber){
var errMsg = "";
var card = getCard();
//var cardNumber = document.getElementById("cardNumber").value;
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMaster = /^5[1-5][0-9]{14}$/;
var regAmerica = /^3[47][0-9]{13}$/;
alert(card); // works till here #######
switch(card){
case "Visa":
if (parseInt(cardNumber.substring(0,1)!=4) {
errMsg = "card number is not visa \n";
}
break;
case "Mastercard":
if (cardNumber.substring(0,1) !=5) {
errMsg = "card number is not mastercard. \n";
}
break;
case "AmericanExpress":
if (cardNumber.substring(0,2) !=51) {
errMsg = "card number not american express, \n";
}
break;
}
return errMsg;
}
function validator(){
var errMsg = ""; /* stores the error message */
var result = true;
var visaCard = document.getElementById("visa").checked;
var masterCard = document.getElementById("mastercard").checked;
var americanExpress = document.getElementById("americanExpress").checked;
var cardName = document.getElementById("cardName").value;
//document.getElementById("cardName").setAttribute('maxlength',40);
var regexAlpha = /^[a-zA-Z ]+$/;
var cardNumber = document.getElementById("cardNumber").value;
var regexNum = /^[0-9]+$/;
var date = new Date();
var todayDateMonth = date.getMonth() + 1;
var todayDateYear = date.getFullYear();
var expMonth = document.getElementById("expMonth").value;
var expYear = document.getElementById("expYear").value;
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMaster = /^5[1-5][0-9]{14}$/;
var regAmerica = /^3[47][0-9]{13}$/;
if (todayDateMonth > expMonth || todayDateYear > expYear){
errMsg += "expiry date is wrong\n";
result = false;
}
if (!(visaCard || masterCard || americanExpress)){
errMsg += "please select visa, mastercard or american express\n";
result = false;
} /* assumes no errors */
if (cardNumber.length > 16 || cardNumber.length < 15 )
{
errMsg = errMsg + "your card number can only contain 15 to 16 digits \n";
result = false;
}else{
checkCard(cardNumber); // Starts here #######
}
if (cardName.length > 40 || cardName.length < 1 || !regexAlpha.test(cardName))
{
errMsg = errMsg + "your card name must only contain alpha characters \n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result; //if false the information will not be sent to the server
}
function init() {
if(document.getElementById("regform")!==null){
var regForm = document.getElementById("regform");// get ref to the HTML element
regForm.onsubmit = validate;
prefill_form();
}
if(document.getElementById("bookform") !=null){
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validator; /* assigns functions to corresponding events */
var cancel = document.getElementById("cancelButton");
cancel.onclick = cancelBooking;
getBooking();
}
}
okay so the problem was that i was not returning an error message or a false result. ill re post the same code as before but what i added to make it work for those interested. thank you for the feed back! i will be taking a few points on board. anyway code is below, look for ###################.
function validator(){
var errMsg = "";
var result = true;
var visaCard = document.getElementById("visa").checked;
var masterCard = document.getElementById("mastercard").checked;
var americanExpress = document.getElementById("americanExpress").checked;
var cardName = document.getElementById("cardName").value;
var regexAlpha = /^[a-zA-Z ]+$/;
var cardNumber = document.getElementById("cardNumber").value;
var regexNum = /^[0-9]+$/;
var date = new Date();
var todayDateMonth = date.getMonth() + 1;
var todayDateYear = date.getFullYear();
var expDate = document.getElementById("expDate").value;
var dateFormat = /^[\d]{2}\/[\d]{4}$/;
if (!dateFormat.test(expDate)){
errMsg += "please select a valid date range\n";
result = false;
}else if (todayDateYear > expDate.substring(3,7)){
errMsg += "please select a valid expiry year\n";
result = false;
} else if (todayDateYear == expDate.substring(3,7) && todayDateMonth > expDate.substring(0,2)){
errMsg += "please select a valid expiry month\n";
result = false;
}
if (!(visaCard || masterCard || americanExpress)){
errMsg += "please select visa, mastercard or american express\n";
result = false;
}
if (cardNumber.length > 16 || cardNumber.length < 15 )
{
errMsg = errMsg + "your card number can only contain 15 to 16 digits \n";
result = false;
}else{
// code below is what i added ######################################
var tempMsg = checkCard(cardNumber);
if (tempMsg != "") {
errMsg = errMsg + tempMsg;
result = false;
};
}
if (cardName.length > 40 || cardName.length < 1 || !regexAlpha.test(cardName))
{
errMsg = errMsg + "your card name must only contain alpha characters \n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result; //if false the information will not be sent to the server
}
function checkCard(cardNumber){
var errMsg = "";
var card = getCard();
var cvv = document.getElementById("CVV").value;
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMaster = /^5[1-5][0-9]{14}$/;
var regAmerica = /^3[47][0-9]{13}$/;
var cvvCheck3 =/^[0-9]{3}$/;
var cvvCheck4 =/^[0-9]{4}$/;
//do with if else
switch(card){
case "Visa":
if (!regVisa.test(cardNumber) || !cvvCheck3.test(cvv)) {
errMsg = "card number is not visa or cvv is wrrong \n";
}
break;
case "Mastercard":
if (!regMaster.test(cardNumber) || !cvvCheck3.test(cvv)) {
errMsg = "card number is not mastercard or cvv is wrong\n";
}
break;
case "AmericanExpress":
if (!regAmerica.test(cardNumber) || !cvvCheck4.test(cvv)) {
errMsg = "card number not american express or cvv is wrong, \n";
}
break;
default:
errMsg = "we cant process this card number \n";
}
return errMsg;
}
The problem is with your code structure I see. You have an if condition inside of switch without any associated else. And without much knowledge of your test conditions I have good reason to believe you are not handling the cases and conditions properly. Simple way to find where your code went wrong is to put debugger; statement in your code. Have your developer tools open, you can do this by pressing F12 in most browsers or just from right click options. It should pause the execution of code there. Then there are two buttons you will see. 1. Play button which will resume code execution at once. 2. Kind of bent arrow, this is important one you can execute code line by line with this one and see which conditions were passed and which part of the code actually executed. Wanted to put this in comment but was too long to fit. If you have problems debugging feel free to comment here.And you can just google developer tools in case you can not open the particular window.
Related
I'm having some trouble with my Javscript for a project (Its own document we're not allowed to use inline JS) my only that I can find while attempting to execute my program is this
"payment.js:182 Uncaught TypeError: Cannot set property 'onsubmit' of null
at init (payment.js:182)".
Now this error does not show up on JSHint when I verify my code so I don't understand how to fix it, it would be great if someone could give me some help. Heres the code:
"use strict";
//validate form inputs from payment.html
function validate() {
var errMsg = "";
var result = true; //assumes no errors
//assign elements to variables
var mastercard_check = document.getElementById("mastercard").checked;
var visa_check = document.getElementById("visa").checked;
var express_check = document.getElementById("express").checked;
var credit_name = document.getElementById("credit_name").value;
var credit_number = document.getElementById("credit_number").value;
var credit_expiry = document.getElementById("credit_expiry").value;
var credit_vv = document.getElementById("credit_vv").value;
//validations for form
if (!(mastercard_check || visa_check || express_check)) {
errMsg += "Please choose a card type\n";
result = false;
}
if (credit_name.length > 40) {
errMsg += "Please enter a name for your credit card between 1-40 characters\n";
result = false;
}
else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
errMsg += "Credit card name can only contain alpha characters\n";
result = false;
}
if (isNaN(credit_number)) {
errMsg = errMsg + "Credit card number must contain digits only\n";
result = false;
}
else if (credit_number.length < 15 || credit_number.length > 16){
errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
result = false;
}
else {
var tempMsg = checkCardNumber(credit_number);
if (tempMsg != "") {
errMsg += tempMsg;
result = false;
}
}
if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
result = false;
}
if (!credit_vv) {
errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
//obtain the credit card type
function getCardType() {
var cardType = "Unknown";
var cardArray = document.getElementById("credit_type").getElementsByTagName("input");
for(var i = 0; i < cardArray.length; i++) {
if (cardArray[i].checked) {
cardType = cardArray[i].value;
}
}
return cardType;
}
//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
var errMsg = "";
var card = getCardType();
switch(card) {
case "visa":
if (!(credit_number.length == 16)) {
errMsg = "Visa number must contian 16 digits\n";
}
else if (!credit_number.match(/^(4).*$/)) {
errMsg = "Visa number must start with a 4. \n";
}
break;
case "mastercard":
if (!(credit_number.length == 16)) {
errMsg = "Mastercard number must contian 16 digits\n";
}
else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
errMsg = "Mastercard number must start with digits 51 through 55. \n";
}
break;
case "express":
if (!(credit_number.length == 15)) {
errMsg = "American Express number must contian 15 digits\n";
}
else if (!credit_number.match(/^(34|37).*$/)) {
errMsg = "American Express number must start with 34 or 37. \n";
}
break;
}
return errMsg;
}
//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
var cost = 0;
if (size.search("three") != -1) cost = 100;
if (size.search("four")!= -1) cost += 150;
if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
var cost = 0;
if(sessionStorage.firstname != undefined){
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;
document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;
document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;
document.getElementById("confirm_package").textContent = sessionStorage.package;
document.getElementById("confirm_size").textContent = sessionStorage.size;
document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
cost = calcCost(sessionStorage.size, sessionStorage.quantity);
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("preferred").value = sessionStorage.preferred;
document.getElementById("deal").value = sessionStorage.deal;
document.getElementById("quality").value = sessionStorage.quality;
document.getElementById("quantity").value = sessionStorage.quantity;
document.getElementById("extrabags").value = sessionStorage.extrabags;
document.getElementById("accomodation").value = sessionStorage.accomodation;
document.getElementById("travel").value = sessionStorage.travel;
document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
}
}
function cancelBooking() {
window.location = "index.html";
}
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = validate;
var cancel = document.getElementById("cancel");
cancel.onclick = cancelBooking;
}
window.onload = init;
It might be that the ID at var payment = document.getElementById("payment"); is wrong and JS can't find it, also if you are calling some function you should do it like this payment.onsubmit = validate(); check that the ID is correct.
make sure your <script> tag is in the last before the </body> tag. like below
<html>
<head>
</head>
<body>
<form>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
but not like this
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
</form>
</body>
</html>
function validatetest(e)
{
debugger;
e.preventDefault();
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var title = document.getElementById("title").value;
var healthNumber = document.getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var telephoneNumber = parseInt(document.getElementById("telephoneNumber").value);
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
var validText = /^[a-zA-Z]*$/;
var validLastText = /^[a-zA-Z-]*$/;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
//var n = healthNumber.startsWith("ZHA");
if(firstName!="" && lastName!= "" && title!="" && email !="")
{
if(email.match(validEmail))
{
if(!isNaN(telephoneNumber) && telephoneNumber >= 11111111111 && telephoneNumber <= 99999999999)
{
if(firstName.match(validText) && firstName.length >1)
{
if(lastName.match(validLastText) && lastName.length> 1)
{
if(healthNumber.match(validHealth))
{
alert("All information is Validated");
return true;
}
else
{
alert("error error");
return false;
}
}
else
{
document.getElementById("error4").innerHTML="letters and hypen only";
return false;
}
}
else
{
document.getElementById("error").innerHTML="letters only and more then one character";
return false;
}
}
else
{
document.getElementById("error2").innerHTML="Telephone number must be 11 num digits long";
}
}
else
{
document.getElementById("error3").innerHTML="email is not a valid format ";
return false;
}
}
else
{
alert("All fields must be entered except telephone Number ");
return false;
}
}
i am trying to create a validation process by using a pattern for a user inputted healthnumber so that it validates whether 3 letters are entered followed by 6 numbers via user input. (MIC123456 is example so MIC always has to been entered , those specific letters)
Not sure if my technique is correct by using a pattern stored in the ValidHeath variable as you can i have used this idea for my email validation etc .
You have an extra + in your regex, make it
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
Demo
var isMatch = !!"IKA111111".match(/^[A-Z]{3}[0-9]{6}$/);
isMatch ? console.log( "Matching" ) : console.log( "Not Matching" );
I am new to learning session storage. At the moment session storage works except for state for my session storage does not work. The state doesn't get displayed once I go to another page or refresh the page, it will go blank like when you are filling in the form for the first time again. Html for state is as shown below. How do I properly code this for a session storage? I also do not want to have any JavaScript library in my code so a solution without it is mch appreciated.
<p><label for="state">*State:</label>
<select name="state" id="state" required="required">
<option value="">Please Select</option>
<option value="state">VIC</option>
<option value="state">NSW</option>
<option value="state">QLD</option>
<option value="state">NT</option>
<option value="state">WA</option>
<option value="state">SA</option>
<option value="state">TAS</option>
<option value="state">ACT</option>
</select></p>
JavaScript:
"use strict";
/*get variables from form and check rules*/
function validate(){
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var firstName = document.getElementById("firstName").value;
var familyName = document.getElementById("familyName").value;
var midName = document.getElementById("midName").value;
var male = document.getElementById("male").checked;
var female = document.getElementById("female").checked;
var street = document.getElementById("street").value;
var suburb = document.getElementById("suburb").value;
var state = document.getElementById("state").options[document.getElementById("state").selectedIndex].text;
var postcode = document.getElementById("postcode").value;
var email = document.getElementById("email").value;
var number = document.getElementById("number").value;
var XML = document.getElementById("XML").checked;
var Java = document.getElementById("Java").checked;
var Python = document.getElementById("Python").checked;
var SQL = document.getElementById("SQL").checked;
var PERL = document.getElementById("PERL").checked;
var MySQL = document.getElementById("MySQL").checked;
var Windows = document.getElementById("Windows").checked;
var UNIX = document.getElementById("UNIX").checked;
var Linux = document.getElementById("Linux").checked;
var other = document.getElementById("other").checked;
var otherText = document.getElementById("otherText").value;
var dob = document.getElementById("dob").value.split("/");
var date = new Date(dob[2], parseInt(dob[1]) - 1, dob[0]);
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
//get varibles from form and check rules here
// if something is wrong set result = false, and concatenate error message
//Validation for Date of birth
if (age >= 80){ // Checks if age is over 80
errMsg = errMsg + "You must be 80 or younger to apply for this job\n";
result = false;
}
if (age <= 15){ // Checks if age is under 15
errMsg = errMsg + "You must be 15 or older to apply for this job\n";
result = false;
}
//Validation for state and corresponding postcode
if (!(postcode.charAt(0) == 3 || postcode.charAt(0) == 8) && state == "VIC") {
errMsg = errMsg + "Your state and postcode do not match. State VIC postcodes must start with a 3 or 8\n";
result = false;
} else if (!(postcode.charAt(0) == 1 || postcode.charAt(0) == 2) && state == "NSW") {
errMsg = errMsg + "Your state and postcode do not match. State NSW postcodes must start with a 1 or 2\n";
result = false;
} else if (!(postcode.charAt(0) == 4 || postcode.charAt(0) == 9) && state == "QLD") {
errMsg = errMsg + "Your state and postcode do not match. State QLD postcodes must start with a 4 or 9\n";
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "NT") {
errMsg = errMsg + "Your state and postcode do not match. State NT postcodes must start with a 0\n";
result = false;
} else if (!(postcode.charAt(0) == 6) && state == "WA") {
errMsg = errMsg + "Your state and postcode do not match. State WA postcodes must start with a 6\n";
result = false;
} else if (!(postcode.charAt(0) == 5) && state == "SA") {
errMsg = errMsg + "Your state and postcode do not match. State SA postcodes must start with a 5\n";
result = false;
} else if (!(postcode.charAt(0) == 7) && state == "TAS") {
errMsg = errMsg + "Your state and postcode do not match. State TAS postcodes must start with a 7\n";
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "ACT") {
errMsg = errMsg + "Your state and postcode do not match. State ACT postcodes must start with a 0\n";
result = false;
} else {
result = true;
}
//Validation of other skill so checks if other skill box is checked and if so will check textbox for text
if (other && document.getElementById("otherText").value.trim().length===0) {
errMsg = errMsg + "You have selected other skills, you must enter one other skill in the text box\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
document.getElementById("error").innerHTML = errMsg;
}
if (result == true) {
storeForm(firstName, familyName, midName, dob, male, female, street, suburb, state, postcode, email, number, XML, Java, Python, SQL, PERL, MySQL, Windows, UNIX, Linux, other, otherText)
}
return result; //if false the information will not be sent to the server
}
function storeForm(firstName, familyName, midName, dob, male, female, street, suburb, state, postcode, email, number, XML, Java, Python, SQL, PERL, MySQL, Windows, UNIX, Linux, other, otherText) {
//get values and assign them to sessionStorage attribute
//used the same name for the attrubute and the element id to avoid confustion
sessionStorage.firstName = firstName;
sessionStorage.familyName = familyName;
sessionStorage.midName = midName;
sessionStorage.dob = dob;
sessionStorage.male = male;
sessionStorage.female = female;
sessionStorage.street = street;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = postcode;
sessionStorage.email = email;
sessionStorage.number = number;
sessionStorage.XML = XML;
sessionStorage.Java = Java;
sessionStorage.Python = Python;
sessionStorage.SQL = SQL;
sessionStorage.PERL = PERL;
sessionStorage.MySQL = MySQL;
sessionStorage.Windows = Windows;
sessionStorage.UNIX = UNIX;
sessionStorage.Linux = Linux;
sessionStorage.other = other;
sessionStorage.otherText = otherText;
}
//check if session day on user exists and if so prefill the form
function prefillForm() {
if (sessionStorage.firstName != undefined) {
document.getElementById("firstName").value = sessionStorage.firstName;
document.getElementById("familyName").value = sessionStorage.familyName;
document.getElementById("midName").value = sessionStorage.midName;
document.getElementById("dob").value = sessionStorage.dob;
if (sessionStorage.male == ("true")) {
document.getElementById("male").checked = true;
}
if (sessionStorage.female == ("true")) {
document.getElementById("female").checked = true;
}
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("number").value = sessionStorage.number;
if (sessionStorage.XML == ("true")) {
document.getElementById("XML").checked = true;
}
if (sessionStorage.Java == ("true")) {
document.getElementById("Java").checked = true;
}
if (sessionStorage.Python == ("true")) {
document.getElementById("Python").checked = true;
}
if (sessionStorage.SQL == ("true")) {
document.getElementById("SQL").checked = true;
}
if (sessionStorage.PERL == ("true")) {
document.getElementById("PERL").checked = true;
}
if (sessionStorage.MySQL == ("true")) {
document.getElementById("MySQL").checked = true;
}
if (sessionStorage.Windows == ("true")) {
document.getElementById("Windows").checked = true;
}
if (sessionStorage.UNIX == ("true")) {
document.getElementById("UNIX").checked = true;
}
if (sessionStorage.Linux == ("true")) {
document.getElementById("Linux").checked = true;
}
if (sessionStorage.other == ("true")) {
document.getElementById("other").checked = sessionStorage.other;
}
document.getElementById("otherText").value = sessionStorage.otherText;
}
}
I have an error message that pops up at the top of my form when something is wrong but the errors stay on the same line. How do I make them go under each other or under the correct place on the web page? I have the below code on my html to display my error message at the moment. If needed I can show my html as well.
<p id="error"></p>
JavaScript:
"use strict";
/*get variables from form and check rules*/
function validate(){
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var firstName = document.getElementById("firstName").value;
var familyName = document.getElementById("familyName").value;
var midName = document.getElementById("midName").value;
var male = document.getElementById("male").checked;
var female = document.getElementById("female").checked;
var street = document.getElementById("street").value;
var suburb = document.getElementById("suburb").value;
var state = document.getElementById("state").options[document.getElementById("state").selectedIndex].text;
var postcode = document.getElementById("postcode").value;
var email = document.getElementById("email").value;
var number = document.getElementById("number").value;
var XML = document.getElementById("XML").checked;
var Java = document.getElementById("Java").checked;
var Python = document.getElementById("Python").checked;
var SQL = document.getElementById("SQL").checked;
var PERL = document.getElementById("PERL").checked;
var MySQL = document.getElementById("MySQL").checked;
var Windows = document.getElementById("Windows").checked;
var UNIX = document.getElementById("UNIX").checked;
var Linux = document.getElementById("Linux").checked;
var other = document.getElementById("other").checked;
var otherText = document.getElementById("otherText").value;
var dob = document.getElementById("dob").value.split("/");
var date = new Date(dob[2], parseInt(dob[1]) - 1, dob[0]);
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
//get varibles from form and check rules here
// if something is wrong set result = false, and concatenate error message
//Validation for Date of birth
if (age >= 80){ // Checks if age is over 80
errMsg = errMsg + "You must be 80 or younger to apply for this job\n";
result = false;
}
if (age <= 15){ // Checks if age is under 15
errMsg = errMsg + "You must be 15 or older to apply for this job\n";
result = false;
}
//Validation for state and corresponding postcode
if (!(postcode.charAt(0) == 3 || postcode.charAt(0) == 8) && state == "VIC") {
errMsg = errMsg + "Your state and postcode do not match. State VIC postcodes must start with a 3 or 8\n";
result = false;
} else if (!(postcode.charAt(0) == 1 || postcode.charAt(0) == 2) && state == "NSW") {
errMsg = errMsg + "Your state and postcode do not match. State NSW postcodes must start with a 1 or 2\n";
result = false;
} else if (!(postcode.charAt(0) == 4 || postcode.charAt(0) == 9) && state == "QLD") {
errMsg = errMsg + "Your state and postcode do not match. State QLD postcodes must start with a 4 or 9\n";
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "NT") {
errMsg = errMsg + "Your state and postcode do not match. State NT postcodes must start with a 0\n";
result = false;
} else if (!(postcode.charAt(0) == 6) && state == "WA") {
errMsg = errMsg + "Your state and postcode do not match. State WA postcodes must start with a 6\n";
result = false;
} else if (!(postcode.charAt(0) == 5) && state == "SA") {
errMsg = errMsg + "Your state and postcode do not match. State SA postcodes must start with a 5\n";
result = false;
} else if (!(postcode.charAt(0) == 7) && state == "TAS") {
errMsg = errMsg + "Your state and postcode do not match. State TAS postcodes must start with a 7\n";
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "ACT") {
errMsg = errMsg + "Your state and postcode do not match. State ACT postcodes must start with a 0\n";
result = false;
} else {
result = true;
}
//Validation of other skill so checks if other skill box is checked and if so will check textbox for text
if (other && document.getElementById("otherText").value.trim().length===0) {
errMsg = errMsg + "You have selected other skills, you must enter one other skill in the text box\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
document.getElementById("error").innerHTML = errMsg;
}
if (result == true) {
storeForm(firstName, familyName, midName, dob, male, female, street, suburb, state, postcode, email, number, XML, Java, Python, SQL, PERL, MySQL, Windows, UNIX, Linux, other, otherText)
}
return result; //if false the information will not be sent to the server
}
#evan
var err = [];
....
....
...
err.push('You have selected other skills, you must enter one other skill in the text box');
....
....
err.push('Your state and postcode do not match. State QLD postcodes
must start with a 4 or 9');
...
// NEW CODE
var ul = document.createElement('ul');
for(var i=0; i< err.length; i++){
var li = document.createElement('li');
li.innerHtml = err[i];
ul.appendChild(li);
}
....
...
var pError = document.getElementById("error");
pError.innerHtml = ul;
I have written this code on the fly .. to the editor here. but i am sure i have clear my point. any doubt post comment below.
I think the better code architecture would be as follows as it gives your more control keeping the sync with your exisiting design.
<ul id="error"></ul>
JavaScript:
"use strict";
/*get variables from form and check rules*/
function validate(){
var errMsgs = []; /* change error message to array */
var result = true; /* assumes no errors */
var firstName = document.getElementById("firstName").value;
var familyName = document.getElementById("familyName").value;
var midName = document.getElementById("midName").value;
var male = document.getElementById("male").checked;
var female = document.getElementById("female").checked;
var street = document.getElementById("street").value;
var suburb = document.getElementById("suburb").value;
var state = document.getElementById("state").options[document.getElementById("state").selectedIndex].text;
var postcode = document.getElementById("postcode").value;
var email = document.getElementById("email").value;
var number = document.getElementById("number").value;
var XML = document.getElementById("XML").checked;
var Java = document.getElementById("Java").checked;
var Python = document.getElementById("Python").checked;
var SQL = document.getElementById("SQL").checked;
var PERL = document.getElementById("PERL").checked;
var MySQL = document.getElementById("MySQL").checked;
var Windows = document.getElementById("Windows").checked;
var UNIX = document.getElementById("UNIX").checked;
var Linux = document.getElementById("Linux").checked;
var other = document.getElementById("other").checked;
var otherText = document.getElementById("otherText").value;
var dob = document.getElementById("dob").value.split("/");
var date = new Date(dob[2], parseInt(dob[1]) - 1, dob[0]);
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
//get varibles from form and check rules here
// if something is wrong set result = false, and concatenate error message
//Validation for Date of birth
if (age >= 80){ // Checks if age is over 80
errMsgs.push("You must be 80 or younger to apply for this job");
result = false;
}
if (age <= 15){ // Checks if age is under 15
errMsgs.push("You must be 15 or older to apply for this job");
result = false;
}
//Validation for state and corresponding postcode
if (!(postcode.charAt(0) == 3 || postcode.charAt(0) == 8) && state == "VIC") {
errMsgs.push("Your state and postcode do not match. State VIC postcodes must start with a 3 or 8");
result = false;
} else if (!(postcode.charAt(0) == 1 || postcode.charAt(0) == 2) && state == "NSW") {
errMsgs.push("Your state and postcode do not match. State NSW postcodes must start with a 1 or 2");
result = false;
} else if (!(postcode.charAt(0) == 4 || postcode.charAt(0) == 9) && state == "QLD") {
errMsgs.push("Your state and postcode do not match. State QLD postcodes must start with a 4 or 9");
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "NT") {
errMsgs.push("Your state and postcode do not match. State NT postcodes must start with a 0");
result = false;
} else if (!(postcode.charAt(0) == 6) && state == "WA") {
errMsgs.push("Your state and postcode do not match. State WA postcodes must start with a 6");
result = false;
} else if (!(postcode.charAt(0) == 5) && state == "SA") {
errMsgs.push("Your state and postcode do not match. State SA postcodes must start with a 5");
result = false;
} else if (!(postcode.charAt(0) == 7) && state == "TAS") {
errMsgs.push("Your state and postcode do not match. State TAS postcodes must start with a 7");
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "ACT") {
errMsgs.push("Your state and postcode do not match. State ACT postcodes must start with a 0");
result = false;
} else {
result = true;
}
//Validation of other skill so checks if other skill box is checked and if so will check textbox for text
if (other && document.getElementById("otherText").value.trim().length===0) {
errMsgs.push("You have selected other skills, you must enter one other skill in the text box");
result = false;
}
if (errMsgs.length > 0) { //only display message box if there is something to show
document.getElementById("error").innerHTML = '<li>' + errMsgs.glue('</li><li>') + '</li>'; /* Apending the error messages as li*/
}
if (result == true) {
storeForm(firstName, familyName, midName, dob, male, female, street, suburb, state, postcode, email, number, XML, Java, Python, SQL, PERL, MySQL, Windows, UNIX, Linux, other, otherText)
}
return result; //if false the information will not be sent to the server
}
I am trying to provide a message below the fields of a form. The message will depend on what is entered in both fields.
How would I go about making it so it calculates in real time using both the fields and passing it through a calculation?
Here is the fiddle http://jsfiddle.net/6qSeH/
I am using this to get the document values
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
and this at the end to run the function
yearCalculator();
There are many missing pieces in your code.
Firstly you have written code entirely using javascript and trying to use jQuery syntax. So how would you expect it to work.
jQuery to set HTML --- msg.html(value);
javascriptto set HTML --- msg.html = value;
Second When you are checking for Not a Number
It is supposed to look like
val1 === NaN // It is not a string
Also this will never work as NaN is never equal to NaN
Use isNaN() method instead
Third
<div class="message"></div>
supposed to be
<div id="message"></div>
Next you need to assign events to your input. Otherwise it would only work when the page loads for the first time..
input1.addEventListener('change', yearCalculator);
input2.addEventListener('change', yearCalculator);
Otherwise it will only work the first time your script loads.
Cleaned up code
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
var msg = document.getElementById('message');
input1.addEventListener('change', yearCalculator);
input2.addEventListener('change', yearCalculator);
function yearCalculator() {
var yearOne = input1.value;
var yearTwo = input2.value;
val1 = parseInt(yearOne);
val2 = parseInt(yearTwo);
if (isNaN(val1) || isNaN(val2)) {
msg.innerHTML = "Please enter a valid year !!";
return;
}
var value1 = yearOne - yearTwo + 18;
if (yearOne == yearTwo) {
msg.innerHTML = "Both years are the same";
}
if (yearOne < yearTwo) {
if (yearTwo < value1) {
msg.innerHTML = "This is a good result";
} else if (yearTwo > value1) {
msg.innerHTML = "This is a bad result";
} else {
msg.innerHTML = "This is neither good or bad";
}
}
else {
msg.innerHTML ="Year 1 is greater than Year 2";
}
};
yearCalculator();
Check Fiddle
You can use onchange="yearCalculator()" in both input fileds
First change the class='message' to id='message'. Then try this code:
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
var yearOne = input1.value;
var yearTwo = input2.value;
var msg = document.getElementById('message');
function yearCalculator(value1, value2) {
msg.innerHTML='';
val1 = parseInt(value1);
val2 = parseInt(value2);
if (val1 === "NAN" || val2 === "NAN") return;
var value1 = val1 - val2 + 18;
if (val1 == val2) {
msg.innerHTML="Both years are the same";
}
if (val1 < val2) {
if (val2 < value1) {
msg.innerHTML = "This is a good result";
} else if (val2 > value1) {
msg.innerHTML = "This is a bad result";
} else {
msg.innerHTML = "This is neither good or bad";
}
}
};
yearCalculator(yearOne,yearTwo);
input1.onkeyup=function() {
yearCalculator(this.value,document.getElementById("input-mini2").value);
};
input2.onkeyup=function() {
yearCalculator(document.getElementById("input-mini").value,this.value);
};