The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> Does this code look correct to you?
Terminator
post Oct 1 2015, 09:25 PM
Post #1


Advanced Member
****

Group: Members
Posts: 218
Joined: 19-March 15
Member No.: 22,398



I am entering this part of the code straight from the book, but it does not work correctly. This book has already had a few mistakes on previous chapters, I wonder if this part of the code is a mistake?

CODE

if ((usernameElement.value !== "" && pass1Element.value !== "" && pass2Element.value !== ""))


Why would they put 2 sets of parenthesis around it?

Besides that I cant see any other issues, It looks like I have all semi-colins entered where they should be. Maybe the catch part is wrong with the 3 if statements under the else statement.

CODE

/* validate create account fieldset */
function validateCreateAccount() {
    var errorDiv = document.querySelector("#createAccount .errorMessage");
    var usernameElement = document.getElementById("username");
    var pass1Element = document.getElementById("pass1");
    var pass2Element = document.getElementById("pass2");
    var passwordMismatch = false;
    var invColor = "rgb(255,233,233)";
    try {
        // reset styles to valid state
        usernameElement.style.background = "";
        pass1Element.style.background = "";
        pass2Element.style.background = "";
        errorDiv.style.display = "none";
        if ((usernameElement.value !== "" && pass1Element.value !== "" && pass2Element.value !== "")) {
            // all fields are filled
            if (pass1Element.value !== pass2Element.value) {
                // passwords dont match
                passwordMismatch = true;
                throw "Passwords entered do not match; please reenter.";
            }
        }
        if (!(usernameElement.value === "" && pass1Element.value === "" && pass2Element.value === "")) {
                // not all fields are blank
                throw "Please complete all fields to create an account.";
            }
    }
    catch(msg) {
        errorDiv.innerHTML = msg;
        errorDiv.style.display = "block";
        if (passwordMismatch) {
            usernameElement.style.background = "";
            pass1Element.style.background = invColor;
            pass2Element.style.background = invColor;
        } else {
            if (usernameElement.value === "") {
                usernameElement.style.background = invColor;
            }
            if (pass1Element.value === "") {
                pass1Element.style.background = invColor;
            }
            if (pass2Element.value === "") {
                pass2Element.style.background = invColor;
            }
        }
        formValidity = false;
    }
}


I have looked over the entire code several times, from what I can see I have typed it exactly as they have it in the book, which is why I think something was left out maybe. And I do have the validateCreateAccount(); function being called in the correct part of the code as well.

This post has been edited by Terminator: Oct 1 2015, 09:29 PM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Oct 2 2015, 05:05 AM
Post #2


.
********

Group: WDG Moderators
Posts: 9,653
Joined: 10-August 06
Member No.: 7



QUOTE(Terminator @ Oct 2 2015, 04:25 AM) *

I wonder if this part of the code is a mistake?

CODE

if ((usernameElement.value !== "" && pass1Element.value !== "" && pass2Element.value !== ""))


Why would they put 2 sets of parenthesis around it?

It's not an error, but I don't think it makes any difference either.

QUOTE
Besides that I cant see any other issues

I think the logic is wrong here:

QUOTE
CODE
        if (!(usernameElement.value === "" && pass1Element.value === "" && pass2Element.value === "")) {
                // not all fields are blank
                throw "Please complete all fields to create an account.";
            }


--it actually checks if all three fields are not empty, and then throws "Please complete all fields", which doesn't make sense. How about something like this instead:

CODE
        if (usernameElement.value === "" || pass1Element.value === "" || pass2Element.value === "") {
                // some fields are blank
                throw "Please complete all fields to create an account.";
            }

Of course this still lets the user enter a blank space or single letter as a username or password...
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Oct 2 2015, 06:42 AM
Post #3


.
********

Group: WDG Moderators
Posts: 9,653
Joined: 10-August 06
Member No.: 7



BTW, sometimes book authors publish error corrections on the publisher's (or author's) website.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Terminator
post Oct 2 2015, 10:48 AM
Post #4


Advanced Member
****

Group: Members
Posts: 218
Joined: 19-March 15
Member No.: 22,398



Thanks

They did publish the known mistakes on their website, but I have already found 3 more mistakes.

The original problem with the book's code is that when you input a username and matching password it still says "Please complete all fields to create an account." and will not let you go to the next page. Your code fixed that, however your code is forcing a username and password every time though. Username is supposed to be optional, this page is for a site like Amazon but they let you purchase without creating a username, so if you leave username and password blank you should be able to go to the next page.

The original book code did work correctly when you left username blank, it let you go to the next page. But original code did not work right when inputting username and matching password.

This post has been edited by Terminator: Oct 2 2015, 10:57 AM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Oct 2 2015, 04:18 PM
Post #5


.
********

Group: WDG Moderators
Posts: 9,653
Joined: 10-August 06
Member No.: 7



QUOTE(Terminator @ Oct 2 2015, 05:48 PM) *

Username is supposed to be optional

That's certainly not how the script is written...

QUOTE
this page is for a site like Amazon but they let you purchase without creating a username, so if you leave username and password blank you should be able to go to the next page.

You mean purchasing without creating an account? In that case, why not simply let the user go to the next page without calling the function validateCreateAccount? The purpose of the function seems to be validating user input when creating an account, so it seems unnecessary to run it if the user's not going to create an account in the first place.

User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Terminator
post Oct 2 2015, 10:23 PM
Post #6


Advanced Member
****

Group: Members
Posts: 218
Joined: 19-March 15
Member No.: 22,398



QUOTE(Christian J @ Oct 2 2015, 04:18 PM) *

You mean purchasing without creating an account? In that case, why not simply let the user go to the next page without calling the function validateCreateAccount? The purpose of the function seems to be validating user input when creating an account, so it seems unnecessary to run it if the user's not going to create an account in the first place.


Yes, I just double checked in the book. It says "this retailer's customers are not required to create accounts, so the Username, Password, and Password Verify Fields can be left blank".

The only way I can proceed to the next page after clicking the place order button with the code from the book is to leave username and password part blank which the book says is supposed to work. But the other part does not work, I get the "Please complete all fields to create an account." error message, when username is typed in with matching passwords.

I am pretty sure this part of the book has several errors that were not stated on the publisher's site. My JavaScript class that uses this book does not start until 3 more weeks, so I will have to wait before showing this to the instructor.

I put the code below from the book if you wanted to check it out. I double checked the validateCreateAccount() part several times, and it matches with how they said to type it in the book. I still have 1 more function to create which I will tomorrow, it is just to verify credit card CVV numbers, and is unrelated to the username function.

Everything below is exactly how the book wanted it typed, so if anything looks real strange it is all on them. I am just starting to learn JavaScript so I cant recognize a lot of logic errors just yet. Thanks for all your help.

CODE


"use strict"; // interpret document contents in JavaScript strict mode

/* global variables */
var twentyNine = document.createDocumentFragment();
var thirty = document.createDocumentFragment();
var thirtyOne = document.createDocumentFragment();
var formValidity = true;

/* set up node building blocks for selection list of days */
function setupDays() {
    var dates = document.getElementById("delivDy").getElementsByTagName("option");
    twentyNine.appendChild(dates[28].cloneNode(true));
    // add 29th
    thirty.appendChild(dates[28].cloneNode(true));
    thirty.appendChild(dates[29].cloneNode(true));
    // add 29th & 30th
    thirtyOne.appendChild(dates[28].cloneNode(true));
    thirtyOne.appendChild(dates[29].cloneNode(true));
    thirtyOne.appendChild(dates[30].cloneNode(true));
    // add 29th 30th, & 31st
}

function updateDays() {
    var deliveryDay = document.getElementById("delivDy");
    var dates = deliveryDay.getElementsByTagName("option");
    var deliveryMonth = document.getElementById("delivMo");
    var deliveryYear = document.getElementById("delivYr");
    var selectedMonth = deliveryMonth.options[deliveryMonth.selectedIndex].value;
    while (dates[28]) {
        // remove child with index of 28 until this index is emptyBoxe
        deliveryDay.removeChild(dates[28]);
    }
    if (deliveryYear.selectedIndex === -1) {
        // if no year is selected, choose the default year so length of Feb can be determined
        deliveryYear.selectedIndex = 0;
    }
    if (selectedMonth === "2" && deliveryYear.options[deliveryYear.selectedIndex].value === "2018") {
        // if leap year, Feb has 29 days
        deliveryDay.appendChild(twentyNine.cloneNode(true));
            } else if (selectedMonth === "4" || selectedMonth === "6" || selectedMonth === "9" || selectedMonth === "11") {
                // these months have 30 days
                deliveryDay.appendChild(thirty.cloneNode(true));
            } else if (selectedMonth === "1" || selectedMonth === "3" || selectedMonth === "5" || selectedMonth === "7" || selectedMonth === "8" || selectedMonth === "10" || selectedMonth === "12") {
                // these months have 31 days
                deliveryDay.appendChild(thirtyOne.cloneNode(true));
            }
}

/* remove default values and formatting from state and delivery date selection lists */
function removeSelectDefaults() {
    var emptyBoxes = document.getElementsByTagName("select");
    for (var i = 0; i < emptyBoxes.length; i++) {
        emptyBoxes[i].selectedIndex = -1;
    }
}

/* remove fallback placeholder text */
function zeroPlaceholder() {
    var messageBox = document.getElementById("customText");
    if (messageBox.value === messageBox.placeholder) {
        messageBox.value = "";
    }
}

/* restore placeholder text if box contains no user entry */
function checkPlaceholder() {
    var messageBox = document.getElementById("customText");
    if (messageBox.value === "") {
        messageBox.style.color = "rgb(178,184,183)";
        messageBox.value = messageBox.placeholder;
    }
}

function generalPlaceholder() {
    if (!Modernizr.input.placeholder) {
        var messageBox = document.getElementById("customText");
        messageBox.value = messageBox.placeholder;
        messageBox.style.color = "rgb(178,184,183)";
        if (messageBox.addEventListener) {
            messageBox.addEventListener("focus", zeroPlaceholder, false);
            messageBox.addEventListener("blur", zeroPlaceholder, false);
        } else if (messageBox.attachEvent) {
            messageBox.attachEvent("onfocus", zeroPlaceholder);
            messageBox.attachEvent("onblur", zeroPlaceholder);
        }
    }
}

/* automatically check Custom message check box if user makes entry in customText box */
function autocheckCustom() {
    var messageBox = document.getElementById("customText");
    if (messageBox.value !== "" && messageBox.value !== messageBox.placeholder) {
        // if user entry in textarea, check Custom check box
        document.getElementById("custom").checked = "checked";
    }
}

/* copy values for Billing Address fields to Delivery Address fields */
function copyBillingAddress() {
    var billingInputElements = document.querySelectorAll("#billingAddress input");
    var deliveryInputElements = document.querySelectorAll("#deliveryAddress input");
    if (document.getElementById("sameAddr").checked) {
        for (var i = 0; i < billingInputElements.length; i++) {
            deliveryInputElements[i + 1].value = billingInputElements[i].value;
        }
        document.querySelector("#deliveryAddress select").value = document.querySelector("#billingAddress select").value;
    } else {
        for (var i = 0; i < billingInputElements.length; i++) {
            deliveryInputElements[i + 1].value = "";
        }
        document.querySelector("#deliveryAddress select").selectedIndex = -1;
    }
}

/* validate address fieldsets */
function validateAddress(fieldsetId) {
    var inputElements = document.querySelectorAll("#" + fieldsetId + " input");
    var errorDiv = document.querySelectorAll("#" + fieldsetId + " .errorMessage")[0];
    var fieldsetValidity = true;
    var elementCount = inputElements.length;
    var currentElement;
    try {
        for (var i = 0; i < elementCount; i++) {
            // validate all input elements in fieldset
            currentElement = inputElements[i];
            if (currentElement.value === "") {
                currentElement.style.background = "rgb(255,233,233)";
                fieldsetValidity = false;
            } else {
                currentElement.style.background = "white";
            }
        }
        currentElement = document.querySelector("#" + fieldsetId + " select");
        // validate state select element
        if (currentElement.selectedIndex === -1) {
            currentElement.style.border = "1px solid red";
            fieldsetValidity = false;
        } else {
            currentElement.style.border = "";
        }
        if (fieldsetValidity === false) {
            // throw appropriate message based on current fieldset
            if (fieldsetId === "billingAddress") {
                throw "Please complete all Billing Address information.";
            } else {
                throw "Please complete all Delivery Address information.";
            }
        } else {
            errorDiv.style.display = "none";
            errorDiv.innerHTML = "";
        }
    }
    catch(msg) {
        errorDiv.style.display = "block";
        errorDiv.innerHTML = msg;
        formValidity = false;
    }
}

/* validate delivery date fieldset */
function validateDeliveryDate() {
    var selectElements = document.querySelectorAll("#deliveryDate select");
    var errorDiv = document.querySelector("#deliveryDate .errorMessage");
    var fieldsetValidity = true;
    var elementCount = selectElements.length;
    var currentElement;
    try {
        for (var i = 0; i < elementCount; i++) {
            currentElement = selectElements[i];
            if (currentElement.selectedIndex === -1) {
                currentElement.style.border = "1px solid red";
                fieldsetValidity = false;
            } else {
                currentElement.style.border = "";
            }
        }
        if (fieldsetValidity === false) {
            throw "Please specify a delivery date.";
        } else {
            errorDiv.style.display = "none";
            errorDiv.innerHTML = "";
        }
    }
    catch(msg) {
        errorDiv.style.display = "block";
        errorDiv.innerHTML = msg;
        formValidity = false;
    }
}

/* validate payment fieldset */
function validatePayment() {
    var errorDiv = document.querySelector("#paymentInfo .errorMessage");
    var fieldsetValidity = true;
    var ccNumElement = document.getElementById("ccNum");
    var selectElements = document.querySelectorAll("#paymentInfo select");
    var elementCount = selectElements.length;
    var cvvElement = document.getElementById("cvv");
    var cards = document.getElementsByName("PaymentType");
    var currentElement;
    try {
        if (!cards[0].checked && !cards[1].checked && !cards[2].checked && !cards[3].checked) {
            // verify that a card is selected
            for (i = 0; i < 4; i++) {
                cards[i].style.outline = "1px solid red";
            }
            fieldsetValidity = false;
        } else {
                for (i = 0; i < 4; i++) {
                cards[i].style.outline = "";
            }
        }
        if (ccNumElement.value === "") {
            // verify that a card number has been entered
            ccNumElement.style.background = "rgb(255,233,233)";
            fieldsetValidity = false;
        } else {
            ccNumElement.style.background = "white";
        }
        for (var i = 0; i < elementCount; i++) {
            // verify that a month and year have been selected
            currentElement = selectElements[i];
            if (currentElement.selectedIndex === -1) {
                currentElement.style.border = "1px solid red";
                fieldsetValidity = false;
            } else {
                currentElement.style.border = "";
            }
        }
        if (cvvElement.value === "") {
            // verify that a cvv value has been entered
            cvvElement.style.background = "rgb(255,233,233)";
            fieldsetValidity = false;
        } else {
            cvvElement.style.background = "white";
        }
        if (!fieldsetValidity) { // check if any field is blank
            throw "Please complete all payment information.";
        } else {
            errorDiv.style.display = "none";
        }
    }
    catch(msg) {
        errorDiv.style.display = "block";
        errorDiv.innerHTML = msg;
        formValidity = false;
    }
}

/* validate message fieldset */
function validateMessage() {
    var errorDiv = document.querySelector("#message .errorMessage");
    var msgBox = document.getElementById("customText");
    try {
        if (document.getElementById("custom").checked && ((msgBox.value === "") || (msgBox.value === msgBox.placeholder))) {
            // custom checked but message box empty
            throw "Please enter your message text.";
        } else {
            errorDiv.style.display = "none";
            msgBox.style.background = "white";
        }
    }
    catch(msg) {
        errorDiv.style.display = "block";
        errorDiv.innerHTML = msg;
        msgBox.style.background = "rgb(255,233,233)";
        formValidity = false;
    }
}

/* validate create account fieldset */
function validateCreateAccount() {
    var errorDiv = document.querySelector("#createAccount .errorMessage");
    var usernameElement = document.getElementById("username");
    var pass1Element = document.getElementById("pass1");
    var pass2Element = document.getElementById("pass2");
    var passwordMismatch = false;
    var invColor = "rgb(255,233,233)";
    try {
        // reset styles to valid state
        usernameElement.style.background = "";
        pass1Element.style.background = "";
        pass2Element.style.background = "";
        errorDiv.style.display = "none";
        if ((usernameElement.value !== "" && pass1Element.value !== "" && pass2Element.value !== "")) {
            // all fields are filled
            if (pass1Element.value !== pass2Element.value) {
                // passwords dont match
                passwordMismatch = true;
                throw "Passwords entered do not match; please reenter.";
            }
        }    
        if (!(usernameElement.value === "" && pass1Element.value === "" && pass2Element.value === "")) {
                // not all fields are blank
                throw "Please complete all fields to create an account.";
            }
    }
    catch(msg) {
        errorDiv.innerHTML = msg;
        errorDiv.style.display = "block";
        if (passwordMismatch) {
            usernameElement.style.background = "";
            pass1Element.style.background = invColor;
            pass2Element.style.background = invColor;
        } else {
            if (usernameElement.value === "") {
                usernameElement.style.background = invColor;
            }
            if (pass1Element.value === "") {
                pass1Element.style.background = invColor;
            }
            if (pass2Element.value === "") {
                pass2Element.style.background = invColor;
            }
        }
        formValidity = false;
    }
}


/* validate form */
function validateForm(evt) {
    if (evt.preventDefault) {
        evt.preventDefault(); // prevent form from submitting
    } else {
        evt.returnValue = false; // prevent form from submitting in IE8
    }
    formValidity = true; // reset value for revalidation
    validateAddress("billingAddress");
    validateAddress("deliveryAddress");
    validateDeliveryDate();
    validatePayment();
    validateMessage();
    validateCreateAccount();
    if (formValidity === true) {
        document.getElementById("errorText").innerHTML = "";
        document.getElementById("errorText").style.display = "none";
        document.getElementsByTagName("form")[0].submit();
    } else {
        document.getElementById("errorText").innerHTML = "Please fix the indicated problems and then resubmit your order.";
        document.getElementById("errorText").style.display = "block";
        scroll(0,0);
    }
}

/* create event listeners */
function createEventListeners() {
    var deliveryMonth = document.getElementById("delivMo");
    if (deliveryMonth.addEventListener) {
        deliveryMonth.addEventListener("change", updateDays, false);
    } else if (deliveryMonth.attachEvent) {
        deliveryMonth.attachEvent("onchange", updateDays);
    }
    var deliveryYear = document.getElementById("delivYr");
    if (deliveryYear.addEventListener) {
        deliveryYear.addEventListener("change", updateDays, false);
    } else if (deliveryYear.attachEvent) {
        deliveryYear.attachEvent("onchange", updateDays);
    }
    var messageBox = document.getElementById("customText");
    if (messageBox.addEventListener) {
        messageBox.addEventListener("blur", autocheckCustom, false);
    } else if (messageBox.attachEvent) {
        messageBox.attachEvent("onblur", autocheckCustom);
    }
    var same = document.getElementById("sameAddr");
    if (same.addEventListener) {
        same.addEventListener("click", copyBillingAddress, false);
    } else if (same.attachEvent) {
        same.attachEvent("onclick", copyBillingAddress);
    }
    var form = document.getElementsByTagName("form")[0];
    if (form.addEventListener) {
        form.addEventListener("submit", validateForm, false);
    } else if (form.attachEvent) {
        form.attachEvent("onsubmit", validateForm);
    }
}

/* run initial form configuration functions */
function setUpPage() {
    removeSelectDefaults();
    setupDays();
    createEventListeners();
    generatePlaceholder();
}

/* run setup function when page finishes loading */
if (window.addEventListener) {
    window.addEventListener("load", setUpPage, false);
} else if (window.attachEvent) {
    window.attachEvent("onload", setUpPage);
}
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Oct 3 2015, 04:22 AM
Post #7


.
********

Group: WDG Moderators
Posts: 9,653
Joined: 10-August 06
Member No.: 7



QUOTE(Terminator @ Oct 3 2015, 05:23 AM) *

I am pretty sure this part of the book has several errors that were not stated on the publisher's site. My JavaScript class that uses this book does not start until 3 more weeks, so I will have to wait before showing this to the instructor.

I wouldn't spend too much time on it then, you'll just confuse yourself...

QUOTE
I put the code below from the book if you wanted to check it out.

Did you write all that down by hand from a book? ohmy.gif

Anyway, the script doesn't show how/when the functions are called, but to me it only makes sense to call the validateCreateAccount() function when the user actually wants to create an account.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Terminator
post Oct 3 2015, 10:26 AM
Post #8


Advanced Member
****

Group: Members
Posts: 218
Joined: 19-March 15
Member No.: 22,398



QUOTE(Christian J @ Oct 3 2015, 04:22 AM) *

Did you write all that down by hand from a book? ohmy.gif

Anyway, the script doesn't show how/when the functions are called, but to me it only makes sense to call the validateCreateAccount() function when the user actually wants to create an account.


Yes, that is how this style of book is, it is similar to that series of books called "New Perspectives on..."
For each chapter while you are reading about something that they are teaching, they also provide the code that you are supposed to type as part of the chapter to create the program or web page.

This is a newer book so no one has typed the code yet online to where I could just copy and paste, and then check for errors. Some instructors use these kind of tutorial books because they think the book will do the teaching for them. So you basically have to teach yourself, and then take the college class just so you can tell some future employer that you took the class, even though you taught yourself.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Oct 3 2015, 11:23 AM
Post #9


.
********

Group: WDG Moderators
Posts: 9,653
Joined: 10-August 06
Member No.: 7



I suppose it's good for memorization to type manually. unsure.gif
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Terminator
post Oct 3 2015, 03:20 PM
Post #10


Advanced Member
****

Group: Members
Posts: 218
Joined: 19-March 15
Member No.: 22,398



I use Notepad++ which has autocomplete, so I don't have to always type or copy and paste stuff that is used often like getElementById.

How else would this be created without typing? Are you trying to say most of this is available with jQuery? That has not been covered in the book yet. The instructor will want us to go in order anyway and do it the hard way first.

This post has been edited by Terminator: Oct 3 2015, 03:21 PM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Oct 3 2015, 04:12 PM
Post #11


.
********

Group: WDG Moderators
Posts: 9,653
Joined: 10-August 06
Member No.: 7



QUOTE(Terminator @ Oct 3 2015, 10:20 PM) *

How else would this be created without typing?

I was thinking of copying online examples. I imagine typing a long script from a printed book may easily results in typos.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 19th April 2024 - 04:50 PM