Having 2 javascript in one html - javascript

I need to have 2 javascript file running on one single HTML file.
<script type="text/javascript" src="scripts/enhancements.js"></script>
<script type="text/javascript" src="scripts/part2-payment.js"></script>
Both of these script will be loaded in my payment.html page
But it is conflicting because it is loading the bottom one rather than the top one.
Script 1 - part2-payment.js
/**
* Author: Kelvin Chong Choon Siong
* Target: payment.html
* Purpose: Validate and carry forward information to Payment.html
* Created: 14 Apr 2017
* Last updated: 17-04-17
*/
"use strict";
function destroyAll(){
sessionStorage.clear();
window.location = "index.html";
}
function calcCost(bikeType, quantity){
var result = "";
if (bikeType == "Road Bicycle (City Bike) $300") {
result = (300) * quantity;
}
if (bikeType == "Cyclocross Bicycle $330") {
result = (330) * quantity;
}
if (bikeType == "Touring Bicycle $310") {
result = (310) * quantity;
}
if (bikeType == "Track/Fixed-Gear Bicycle $380") {
result = (380) * quantity;
}
if (bikeType == "Mountain Bicycle $340") {
result = (340) * quantity;
}
if (bikeType == "BMX Bicycle $380") {
result = (380) * quantity;
}
if (bikeType == "Folding Bicycle $450") {
result = (450) * quantity;
}
if (bikeType == "Tandem Bicycle $600") {
result = (600) * quantity;
}
return result;
}
function getBooking(){
if(sessionStorage.fname != undefined){ //if sessionStorage for username is not empty
//confirmation text
document.getElementById("fname").textContent = sessionStorage.fname + " " + sessionStorage.lname;
document.getElementById('address').textContent = sessionStorage.address + ", " + sessionStorage.suburb + ", " + sessionStorage.state + ", " + sessionStorage.postcode;
document.getElementById('emailadd').textContent = sessionStorage.emailadd;
document.getElementById('phonenumber').textContent = sessionStorage.pnumber;
document.getElementById('features').textContent = sessionStorage.extra;
document.getElementById('comments').textContent = sessionStorage.comments;
document.getElementById('type_bike').textContent = sessionStorage.bikeType;
document.getElementById('quantity1').textContent = sessionStorage.quantity;
document.getElementById('sizez').textContent = sessionStorage.size;
document.getElementById('cost').textContent = ("AU$ " + calcCost(sessionStorage.bikeType, sessionStorage.quantity));
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.fname;
document.getElementById("lastname").value = sessionStorage.lname;
document.getElementById("emailAddress").value = sessionStorage.emailadd;
document.getElementById("homeAddress").value = sessionStorage.address;
document.getElementById("suburbs").value = sessionStorage.suburb;
document.getElementById("states").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("radioButtons").value = sessionStorage.radiobutton;
document.getElementById("pnumber").value = sessionStorage.pnumber;
document.getElementById("type_bike[]").value = sessionStorage.bikeType;
document.getElementById("quantity[]").value = sessionStorage.quantity;
document.getElementById("size[]").value = sessionStorage.size;
document.getElementById("costFinal").value = calcCost(sessionStorage.bikeType, sessionStorage.quantity)
document.getElementById("extraFeature").value = sessionStorage.extra;
document.getElementById("comment").value = sessionStorage.comments;
}
}
function cardExpiry(){
var errMsg = "";
var getExpiryDate = document.getElementById("expirydate").value;
var getMonth = String(getExpiryDate).charAt(0) + String(getExpiryDate).charAt(1);
var getYear = String(getExpiryDate).charAt(3) + String(getExpiryDate).charAt(4);
var dateNow = new Date ();
var expiryInput = new Date();
expiryInput.setFullYear('20' + getYear, getMonth-1, 1);
if (expiryInput < dateNow){
errMsg = "Your expiration date is before current date. Please change it.\n"
}
return errMsg;
}
function cardValidation() {
/*Visa cards have 16 digits and start with a 4
MasterCard have 16 digits and start with digits 51 through to 55
American Express has 15 digits and starts with 34 or 37.*/
var errMsg = "";
var cardNumber = document.getElementById('cardnum').value;
var cardType = document.getElementById('cardType').value;
var number0 = String(cardNumber).charAt(0);
var number1 = String(cardNumber).charAt(1);
switch (cardType) {
case "Visa":
if ((number0 !== "4") || (cardNumber.length !== 16)) {
errMsg = "Visa cards have 16 digits and start with a 4.\n";
}
break;
case "Mastercard":
if (((number0) !== "5") || ((number1) !== "1" && ((number1) !== "2") && ((number1) !== "3") && ((number1) !== "4") && ((number1) !== "5") ) || (cardNumber.length !== 16)) {
errMsg = "MasterCard have 16 digits and start with digits 51 through to 55.\n";
}
break;
case "Amex":
if (((number0) !== "3") || ((number1) !== "4" && ((number1) !== "7")) || (cardNumber.length !== 15)) {
errMsg = "Amex cards have 15 digits and start with a 34 or 37.\n";
}
break;
default:
errMsg = "Please write your correct card number.\n";
}
return errMsg;
}
function cvvValidation(){
var errMsg = "";
var cardType = document.getElementById('cardType').value;
var cvvcheck = document.getElementById('CVV').value;
//3 digits, for Visa and Mastercard, 4 digits for American Express.
switch (cardType) {
case "Visa":
if (cvvcheck.length !== 3) {
errMsg = "Visa cards have a CVV of 3 digits.\n";
}
break;
case "Mastercard":
if (cvvcheck.length !== 3) {
errMsg = "MasterCards have a CVV of 3 digits.\n";
}
break;
case "Amex":
if (cvvcheck.length !== 4) {
errMsg = "Amex cards have a CVV of 4 digits..\n";
}
break;
default:
errMsg = "Please write your correct card CVV.\n";
}
return errMsg;
}
function validate() {
var errMsg = "";
var result = true;
var checkCard = cardValidation();
if (checkCard !== "") {
errMsg = errMsg + checkCard;
result = false ;
}
var checkCVV = cvvValidation();
if (checkCVV !== "") {
errMsg = errMsg + checkCVV;
result = false ;
}
var checkExpiry = cardExpiry();
if (checkExpiry !== ""){
errMsg = errMsg + checkExpiry;
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
function init() {
getBooking();
var regForm = document.getElementById("form2");
regForm.onsubmit= validate;
var destroyEverything = document.getElementById('cancelout');
destroyEverything.onclick = destroyAll;
}
window.onload = init;
So this is Script 2 now
Script 2 - enhancements.js
"use strict";
function writeNewMessage(){
var sMessage = document.getElementById('spanny');
sMessage.textContent = "this is a test";
}
function init2() {
var labelTest = document.getElementById("booking_form");
labelTest.onclick = writeNewMessage;
}
window.onload = init2;
I can't figure out how to load both in at the same time.
A few restrictions that I have (because most of the solutions provided on the net I can't use)
body onload
No Inline javascript
No jQuery
So I was wondering if there is another one to make both work?

Your onloads are overwriting each other:
window.onload = init2;//will override window.onload=init;
So do:
window.addEventListener("load",init2);
Same for all the other clicks, etc.

Managed to figure it out by using
window.onload = function() {
init();
init2();
};
doing this on either one of the js script would work.
All good. On n'est jamais mieux servi que par soi-meme.

Related

i dont know ho to do this freecodecamp javascript calculator

help !! the console tells me x13. If 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (-) sign. The sequence"5-5"=should produce an output of"-25"expected'-5'to equal¹-25'
AssertionError:The sequence"5-5"=should produce an output of"-25"expected'-5'to equal
I try to use regex because someone tells me I should do that but I don't know how. I do 15 right but one is wrong and I can't pass this test :(
https://codepen.io/mikaelamattos/pen/RwQGeXe
let trailingResult = 0;
let operationOptions = ['divide', 'multiply', 'subtract', 'add'];
let workingOperation = "";
function updateDisplay(input) {
let display = document.getElementById("display");
let secondaryDisplay = document.getElementById("secondaryDisplay");
if (display.innerHTML === "0" && operationOptions.indexOf(input) === -1) {
if (input === "decimal") {
display.innerHTML = "0.";
} else if (input === "negative-value") {
if (display.innerHTML.indexOf("-1") === -1) {
display.innerHTML = "-" + display.innerHTML
} else if (display.innerHTML.indexOf("-1" > -1)) {
display.innerHTML = display.innerHTML.slice(1, display.innerHTML.length);
}
} else {
display.innerHTML = input;
}
} else if (operationOptions.indexOf(input) >= 0) {
if (trailingResult === display.innerHTML) {
workingOperation = input;
} else if (workingOperation === "") {
workingOperation = input;
trailingResult = display.innerHTML;
secondaryDisplay.innerHTML = trailingResult;
display.innerHTML = 0;
} else {
// Dealing with a set operand
// console.log(display.innerHTML, " Dealing with set operand");
trailingResult = calculate(trailingResult, display.innerHTML, workingOperation);
secondaryDisplay.innerHTML = trailingResult;
display.innerHTML = 0;
workingOperation = input;
}
} else if (input === "equals") {
display.innerHTML = calculate(trailingResult, display.innerHTML, workingOperation);
trailingResult = 0;
workingOperation = "";
secondaryDisplay.innerHTML = trailingResult;
} else if (input === "decimal") {
// console.log('decimal clicked');
if (display.innerHTML.indexOf(".") === -1) {
display.innerHTML += ".";
}
// console.log("decimal skipped because decimal already in number.");
} else if (input === "negative-value") {
// console.log("negative-value selected");
if (display.innerHTML.indexOf("-1") === -1) {
display.innerHTML = "-" + display.innerHTML
} else if (display.innerHTML.indexOf("-1" > -1)) {
display.innerHTML = display.innerHTML.slice(1, display.innerHTML.length);
}
} else {
display.innerHTML += input;
}
}
function clearDisplay() {
let display = document.getElementById("display");
let secondaryDisplay = document.getElementById("secondaryDisplay");
trailingResult = 0;
display.innerHTML = 0;
secondaryDisplay.innerHTML = trailingResult;
}
function calculate(firstNumber, secondNumber, operation) {
let result;
firstNumber = parseFloat(firstNumber);
secondNumber = parseFloat(secondNumber);
switch(operation) {
case "add":
result = firstNumber + secondNumber;
break;
case "subtract":
result = firstNumber - secondNumber;
break;
case "multiply":
result = firstNumber * secondNumber;
break;
case "divide":
result = firstNumber / secondNumber;
break;
default:
console.log("Calculate switch statement missed something");
}
return result.toString();
}

Beginner Javascript errors 'Line is longer than 80 characters', 'unexpected var' and 'use space not tabs'

Having trouble with a combined file of html, CSS and javascript that is giving me an undisclosed error, used JSLint to check for errors but the only errors I were given were 'Line is longer than 80 characters', 'use spaces not tabs' and 'unexpected var'. Could someone please give me some help I'm real stuck.
"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 = function() {validate()};
var cancel = document.getElementById("cancel");
cancel.onclick = function cancelBooking()
}
window.onload = init;
it's common rule of eslint, if you want to ignore these error on you code, you can use eslint-disable on top of your js code
/* eslint-disable */
alert('foo');
The problem is inside your init() function. I have corrected it please try using this. You were calling the function cancelBooking() like this function cancelBooking() which was giving error.
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = function() {validate()};
var cancel = document.getElementById("cancel");
cancel.onclick = cancelBooking()
}

I am writing a hangman program in java script and need help getting the word to display if the player loosed

Here is the javascript code:
I need help getting the word to display after the player looses.
var can_play = true;
//this is the array of words
var words = new Array("VALIDATE", "DESIGN", "INPUT", "ARRAY", "OBJECT", "DOCUMENTATION", "JQUERY", "CALCULATE", "ABSOLUTE", "DREAMWEAVER", "BROWSER", "HTML", "CONCATINATION");
var display_word = "";
var used_letters = "";
var wrong_guesses = 0;
//this will allow the letters to be entered in only 1 time
function selectLetter(l) {
if (can_play == false) {
return;
}
if (used_letters.indexOf(l) != -1) {
return;
}
used_letters += l;
document.game.usedLetters.value = used_letters;
if (to_guess.indexOf(l) != -1) {
// this will display the correct letter guesses
pos = 0;
temp_mask = display_word;
while (to_guess.indexOf(l, pos) != -1) {
pos = to_guess.indexOf(l, pos);
end = pos + 1;
start_text = temp_mask.substring(0, pos);
end_text = temp_mask.substring(end, temp_mask.length);
temp_mask = start_text + l + end_text;
pos = end;
}
display_word = temp_mask;
document.game.displayWord.value = display_word;
if (display_word.indexOf("*") == -1) {
// this will display a message if you win
$('#win').html("Well done, you won!");
can_play = false;
}
} else {
// this will display the incorrect letter guesses
wrong_guesses += 1;
$('#wrong_guesses').html(wrong_guesses);
if (wrong_guesses == 6) {
// this will display a message if you loose
$('#win').html("Sorry, you have lost!");
can_play = false;
}
}
}
//this will reset the game to play again
function reset() {
selectWord();
document.game.usedLetters.value = "";
guessed_letters = "";
wrong_guesses = 0;
$('#win').html("");
$('#wrong_guesses').html("");
}
//this will have the computer select a word from my array
function selectWord() {
can_play = true;
random_number = Math.round(Math.random() * (words.length - 1));
to_guess = words[random_number];
// this will display mask
masked_word = createMask(to_guess);
document.game.displayWord.value = masked_word;
display_word = masked_word;
}
function createMask(m) {
mask = "";
word_length = m.length;
for (i = 0; i < word_length; i++) {
mask += "*";
}
return mask;
}
$('#win').html("Sorry, you have lost, the word was " + to_guess + "!");
You assigned the to be guessed word here:
to_guess = words[random_number];
You would learn much from posting your code to Code Review.

Adding price to total when checkbox is selected

I would like to add a $5.00 charge whenever the txtBwayEDUGift checkbox is selected. The javascript code I currently have is reducing the amount when checkbox is unchecked, but not applying the charge when selected. I can provide additonal code if needed.
Here is my input type from my aspx page:
<input type="checkbox" name="txtBwayEDUGift" id="txtBwayEDUGift" onchange="checkboxAdd(this);" checked="checked" />
Here is my javascript:
{
var divPrevAmt;
if (type == 0)
{
divPrevAmt = document.getElementById("divBwayGiftPrevAmt");
}
else if (type == 1)
{
divPrevAmt = document.getElementById("divBwayEDUGiftPrevPmt");
}
var txtAmt = document.getElementById(obj);
var amt = txtAmt.value;
amt = amt.toString().replace("$","");
amt = amt.replace(",","");
var prevAmt = divPrevAmt.innerHTML;
try
{
amt = amt * 1;
}
catch(err)
{
txtAmt.value = "";
return;
}
if (amt >= 0) //get the previous amount if any
{
if (type == 0)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
else if (type == 1)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
//now update the master total
var total = document.getElementById("txtTotal");
var dTotal = total.value.toString().replace("$","");
dTotal = dTotal.replace(",","");
dTotal = dTotal * 1;
var newTotal = dTotal - prevAmt;
newTotal = newTotal + amt;
divPrevAmt.innerHTML = amt.toString();
newTotal = addCommas(newTotal);
amt = addCommas(amt);
txtAmt.value = "$" + amt;
total.value = "$" + newTotal;
}
else
{
txtAmt.value = "";
return;
}
}
function disable()
{
var txtTotal = document.getElementById("txtTotal");
var txt = txtTotal.value;
txtTotal.value = txt;
var BwayGift = document.getElementById("txtBwayGift");
BwayGift.focus();
}
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var newTotal = x1 + x2;
if (newTotal.toString().indexOf(".") != -1)
{
newTotal = newTotal.substring(0,newTotal.indexOf(".") + 3);
}
return newTotal;
}
function checkChanged()
{
var cb = document.getElementById("cbOperaGala");
if (cb.checked == true)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "url('images/otTableRowSelect.jpg')";
}
else if (cb.checked == false)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "";
}
}
function alertIf()
{
var i = 0;
for (i=5;i<=10;i++)
{
try{
var subtotal2 = document.getElementById("txtSubTotal" + i);
var dSubtotal2 = subtotal2.value;
dSubtotal2 = dSubtotal2.replace("$","");
dSubtotal2 = dSubtotal2 * 1;}
catch (Error){dSubtotal2 = 0}
if (dSubtotal2 > 0)
{
alert("You have selected the I want it all package, \n however you have also selected individual tickets to the same events. \n If you meant to do this, please disregard this message.");
break;
}
}
}
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
//Add $5.00 donation to cart
function checkboxAdd(ctl) {
if (ctl.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal( 5, "S");
}
}
</script>
I do not understand the context of the scenario. When a user clicks the checkbox are you making an HTTP request to the server? Or is this a simple form POST page? What is calculateTotal() doing?
I figured it out. So the functionality I had in place was fine.
//Add $5.00 donation to cart
function checkboxAdd(txtBwayEDUGift) {
if (txtBwayEDUGift.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal(5, "S");
}
}
But I needed to add a load function:
function load() {
calculateTotal(5, "A");
}
<body onload="load()">
Along with adding a reference to my c# page:
if (txtBwayEDUGift.Checked)
{
addDonations(5.00, 93);
}
You can use jQuery :)
$(txtBwayEDUGift).change(calculateTotal(5, "S"));

Need help simplyfying validation

I need help with simplifying/making shorter of the following validation code.
Help would be greatly appreciated.
At the moment there's too much text, my teacher said it could be done easier/cleaner...
I'm really stuck.
Thank you.
window.addEventListener('load',init,false);
function init(){
var submit = document.getElementById("submit");
var gender = document.getElementById("gender");
var age = document.getElementById("age");
var length = document.getElementById("length");
var weight = document.getElementById("weight");
var duration = document.getElementById("duration");
var time = document.getElementById("time");
submit.addEventListener('click', validation, false);
gender.addEventListener('checked',validategender,false);
age.addEventListener('blur', validateage, false);
length.addEventListener('blur',validatelength,false);
weight.addEventListener('blur',validateweight,false);
duration.addEventListener('blur',validateduration,false);
time.addEventListener('checked',validatetime,false);
}
function validategender(){
var man = document.getElementById("man");
var vrouw = document.getElementById("vrouw");
var genderfout = document.getElementById("genderFout");
if(man.checked != true && vrouw.checked !=true){
genderfout.innerHTML = "Please choose a gender";
return false;
}else {
genderfout.innerHTML = "";
}return true;
}
function validateage() {
var age = parseInt(document.getElementById("age").value, 10);
var ageFout = document.getElementById("ageFout");
if (isNaN(age) || age < 0 || age > 130) {
ageFout.innerHTML = "Please enter a valid age";
return false;
} else {
ageFout.innerHTML = "";
}
return true;
}
function validateweight() {
var weight = parseInt(document.getElementById("weight").value, 10);
var weightFout = document.getElementById("weightFout");
if (isNaN(weight) || weight < 30 || weight > 200) {
weightFout.innerHTML = "Please enter a valid weight";
return false;
} else {
weightFout.innerHTML = "";
}
return true;
}
function validatelength() {
var length = parseInt(document.getElementById("length").value, 10);
var lengthFout = document.getElementById("lengthFout");
if (isNaN(length) || length < 50 || length > 220) {
lengthFout.innerHTML = "Please enter a valid length";
return false;
} else {
lengthFout.innerHTML = "";
}
return true;
}
function validateduration() {
var duration = parseInt(document.getElementById("duration").value, 10);
var durationFout = document.getElementById("durationFout");
if (isNaN(duration) || duration < 0) {
durationFout.innerHTML = "Please enter a valid time-duration";
return false;
} else {
durationFout.innerHTML = "";
}
return true;
}
function validatetime(){
var minutes = document.getElementById("minutes");
var hours = document.getElementById("hours");
var timeFout = document.getElementById("timeFout");
if(minuten.checked !=true && uur.checked !=true){
timeFout.innerHTML = "choose a time unit!";
return false;
}else {
timeFout.innerHTML = "";
}
return true;
}
function validation(e){
var genderOk = validategender();
var ageOk = validateage();
var weightOk = validateweight();
var lengthOk = validatelength();
var durationOk = validateduration();
var timeOk = validatetime();
if (!genderOk || !ageOk || !weightOk || !lengthOk || !durationOk || !timeOk){
e.preventDefault();
}
}
if JQuery not allowed that leave another option
Regular expression
you can validate but needs a little reading
Use a JQuery validator
http://docs.jquery.com/Plugins/Validation
Your validation code will be reduced to half of what it is now or possibly much less.

Categories