Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Where can I put an (if) statement that says "once the form is valid, alert a success message to the user"....

I have validated each field in this form to return true if the user has entered info in every field, but I am stuck towards the bottom. I want to send an alert message back to the user once the form is valid and submitted. I have tried multiple if statements and have had no success. I am not sure if I am placing the if statement in the wrong location, of if the IF statement in itself is wrong based on the condition.

Please help.

Here is my JS code....

function validate(formValid) {

// NEW: move this way up here so all validations can affect its value:
var formValid = true;

// function to check if a name has been entered
var name = document.getElementById('name').value;

if (name == null || name.trim() == "") {
    document.getElementById('nameerror').innerHTML = "Please enter your full name";
    formValid = false;
} else {
    document.getElementById('nameerror').innerHTML = "";
}

// function to check if an email has been entered
var email = document.getElementById('email').value;

if (email == null || email.trim() == "") {
    document.getElementById('emailerror').innerHTML = "Please enter your email address";
    formValid = false;
} else {
    document.getElementById('emailerror').innerHTML = "";
}

// function to check if a telephone number has been provided
var phone = document.getElementById('phone').value;

if (phone == null || phone.trim() == "") {
    document.getElementById('phoneerror').innerHTML = "Please enter your telephone number";
    formValid = false;
} else {
    document.getElementById('phoneerror').innerHTML = "";
}

//validate the select options
var select = document.getElementById('select').value;
    if (select == '') {
        document.getElementById('selecterror').innerHTML = "Please make a selection";
        formValid = false;
    } else {
        document.getElementById('selecterror').innerHTML = "";

    }



//function to validate the textarea field
var name = document.getElementById('textarea').value;

if (name == null || name.trim() == "") {
    document.getElementById('textareaerror').innerHTML = "Please enter additional info";
    formValid = false;
} else {
    document.getElementById('textareaerror').innerHTML = "";
}
// function to validate if any radio button has been selected
var radios = document.getElementsByName('radio');
var radiosValid = false;
var i = 0;

while (!radiosValid && i < radios.length) {
    if (radios[i].checked) radiosValid = true;
    i++;
}

if (!radiosValid) {
    document.getElementById('radioerror').innerHTML = "(Please check one)";
    formValid = false;
} else {
    document.getElementById('radioerror').innerHTML = "";
}

// function to confirm if any checkbox has been checked
var checkboxes = document.getElementsByName('checkbox');
var checkboxesValid = false;
var j = 0;

while (!checkboxesValid && j < checkboxes.length) {
    if (checkboxes[j].checked) checkboxesValid = true;
    j++;
}

if (!checkboxesValid) {
    document.getElementById('checkboxerror').innerHTML = "(Please select at least one)";
    formValid = false;
} else {
    document.getElementById('checkboxerror').innerHTML = "";

}
// now that all validations have run, return the submit message

if (formValid) {
    alert("Congrats");
}

}

11 Answers

Oh, you could use a counter to keep track of invalid fields, and at the end if the counter stays 0, then all fields are valid and you can show the alert. Also try wrapping that whole validation process in a single function and have the if statement at the bottom so it gets called after the validation. I would also recommend calling this function on the onsubmit handler of the form so you can pass in the form with "this" keyword

validate(this){ 
    var counter = 0;

//include in validation process...
    if(!fieldvalid){
        counter++;
    }

///after validation process

    if(counter === 0){
        alert("congrats");
    }
}

I hope I understood what you meant.

Javascript runs line by line from top to bottom, except in special cases where certain lines may take longer to execute than other in which case it will continue to wait and the the est of your code without waiting for previous statements to finish executing. That being said you start your function with formValid being true, setup the counter then immediately check if the formVliad is false, and since nothing changed that varable to false, itll always skip over that if statement.

The idea was to increment the counter variable in each if statemen you use to check a field, like

if (name == null || name.trim() == "") {
    document.getElementById('nameerror').innerHTML = "Please enter your full name";
    counter++;
} else {
    document.getElementById('nameerror').innerHTML = "";
}

if (email == null || email.trim() == "") {
    document.getElementById('emailerror').innerHTML = "Please enter your email address";
    counter++;
} else {
    document.getElementById('emailerror').innerHTML = "";
}
//And so on...

That way the counter can accumulate from each invalid field, then when it checks the counter at the bottom, counter will have an appropriate value. Currently counter will always remain 0 since you only try to increment it once in that beginning if statement, but that statement will never evaluate to true. Even when you change formValid, that if statement wont be called again, since this function only runs once as they hit submit. So even if there are invalid fields, the counter is still 0 and the if at the bottom is true, and the alert will be thrown.

However you mentioned the alert is thrown before the field actually get validated, which brings me back to the first part of this answer. The validation checks may be more taxing on the computer then just throwing the alert. By that i mean it may take longer for the computer to loop through your radio buttons and checkboxes that it is to check a simple if statement, So javascript, being an event driven language, wont wait for those loops to finish before moving on to the next lines of code, resulting in code further down your file finish executing before code higher up. I hope that makes sense.

To solve that problem, you can create a callback function, which is a function that forced to excute after another function, making it wait for the first function to finish. There are courses here at treehouse on it like this Treehouse callback function, but its very simple to do.

First create another function in the same file but outside of your validate function, this will be the callbackfunction that checks the counter and throws the congrats alert.

function checkCounter(counter){
    if(counter === 0){
        alert('Congrats');
    }
}

Then add to your validate function another parameter that is the name of your callback function, but put it without parenthesis. And at the bottom of your validate function after all the field have been checked and validated, and counter has accumulated anything, call your callbackfunction and pass in the counter. like so

function validate(formValid, checkCounter) {
//All
//    Your
//        Validation
//              Code

    checkCounter(counter);
}

By doing this, this will force all your validation to execute and finish before you check the counter. That way the alert, if all fields are valid, should be thrown after all the fields have been checked.

Good luck man, I hope this works, if not, please feel free to post more questions. I'm always happy to help. You're doing great and practice makes perfect.

Cool, so the main problem I see revolves around the submit button. Using the input element can work, but its better to use an actual button element. It has attributes that connects it to the form. Also the validate function gets called on an onsubmit handler, the thing about submit is that it refreshed the page. I placed a lot of consolelogs in your if statements when you check each field and noticed it shows then disappear as the page refreshes really fast, so the alert and any error messages you set gets removed. You can remove that on submit in the form element completely.

The way i fixed it was by changing the input element of type submit into a button element of type button, then i connected it to the form, via form attribute. Then added an onclick handler to call validate form. Type button doesnt refresh the page, so the alert and the error message stay. Also I was wrong about the callback, its not necessary having that second parameter call another function. The counter at the top of the function and having the check at the bottom works fine. Here is what the button element looks like

<div class="sendRequest" id="contact-submit">
    <button type="button" form="contactForm"  onclick="validate()"> Send Request </button>
</div>

The formValid boolean parameter isnt necessary, since a valid form will depend on weather the counter is 0 or not. Hopefully this solves it for you too, the rest of your code pretty good too. Except that script tag that gets an element by id 'namehint', that element doesnt exist and will through an error. But your website looks good. Good luck man! Feel free to add a comment if anything else comes up or you have more questions.

No problem im glad it works, and no need to pay me. Helping you helps me learn more about the language. To deal with the refreshing issue, you can put button type back to submit and keep the onsubmit handler on the form, and have it return validate() like the way you originally had it.

Then in your validate function at the bottom where you check the counter,

if(counter === 0 ){
    alert('Congrats!');
    return true;
}
else{
    return false;
}

Returning false will prevent the submit from refreshing, which will allows your error messages to stay, and returning true will submit the form with the refresh. I should of started with that but honestly i didnt even learn that till recently because of this post, im mainly in the backend at work, thanks :D

Search engines are your greatest ally in the world of programming.

PS Can you best answer anyone of my answers, thanks

Hey Dale,

If in your HTML your form field is inside a form Element, you can add the "required" attribute to any of your input elements and that will make the form validate for you before submission which will check if those fields are empty. This will work for checkboxes and radio buttons too.

<input type="text" id="name" name="firstName" required />

Alternatively you can have a onsubmit eventhandler on the form element and have it call a validateForm function, then you can access the elements of the form in js with the documents.forms["formName"]

<form name="formName" onsubmit="validateForm()"> </form>
function validateForm(){
     var form = document.forms["formName"]; //This is an array with all your input elements inside
     var counter = 0; //counts invalid fields

    for(i = 0; i < form.length; i++){
        //this would only be useful for text, textarea, email, and password inputs
        if( form[i].value === "" ) { 
            counter++;
        }
    }

    if(counter === 0){
        alert("congrats");
    }
    else{
        alert("There  are some invalid fields");
    }

}

I have achieved validating my form, I just was looking for some help for using an IF statement that'll return a success message to the user. All of the code I posted works, except for the IF statement at the bottom where I am trying to return a success message. That is where I am stuck.

I had to validate each form field individually due to project requirements, but I am having a hard time coming up with the solution to return a success message in my code.

I think you understand it. I'll make these adjustments to my code in a little while and then post back if it works or not.

Hey Emmanuel, I tried implementing the code. I am now getting the alert that I was looking for, but I am getting that alert BEFORE the form is validated. I want to get the from to validate first, and then if all of the form has been successfully filled out, return the congrats alert after they hit submit.

Here is my code.....

document.addEventListener("DOMContentLoaded", function (event) { alert("This page is best viewed with JavaScript enabled"); });

function validate(formValid) {

// NEW: move this way up here so all validations can affect its value:
var formValid = true;
var counter = 0;
if (!formValid) {
    counter++;
}
// function to check if a name has been entered
var name = document.getElementById('name').value;

if (name == null || name.trim() == "") {
    document.getElementById('nameerror').innerHTML = "Please enter your full name";
    formValid = false;
} else {
    document.getElementById('nameerror').innerHTML = "";
}

// function to check if an email has been entered
var email = document.getElementById('email').value;

if (email == null || email.trim() == "") {
    document.getElementById('emailerror').innerHTML = "Please enter your email address";
    formValid = false;
} else {
    document.getElementById('emailerror').innerHTML = "";
}

// function to check if a telephone number has been provided
var phone = document.getElementById('phone').value;

if (phone == null || phone.trim() == "") {
    document.getElementById('phoneerror').innerHTML = "Please enter your telephone number";
    formValid = false;
} else {
    document.getElementById('phoneerror').innerHTML = "";
}

//validate the select options
var select = document.getElementById('select').value;
    if (select == '') {
        document.getElementById('selecterror').innerHTML = "Please make a selection";
        formValid = false;
    } else {
        document.getElementById('selecterror').innerHTML = "";

    }



//function to validate the textarea field
var name = document.getElementById('textarea').value;

if (name == null || name.trim() == "") {
    document.getElementById('textareaerror').innerHTML = "Please enter additional info";
    formValid = false;
} else {
    document.getElementById('textareaerror').innerHTML = "";
}
// function to validate if any radio button has been selected
var radios = document.getElementsByName('radio');
var radiosValid = false;
var i = 0;

while (!radiosValid && i < radios.length) {
    if (radios[i].checked) radiosValid = true;
    i++;
}

if (!radiosValid) {
    document.getElementById('radioerror').innerHTML = "(Please check one)";
    formValid = false;
} else {
    document.getElementById('radioerror').innerHTML = "";
}

// function to confirm if any checkbox has been checked
var checkboxes = document.getElementsByName('checkbox');
var checkboxesValid = false;
var j = 0;

while (!checkboxesValid && j < checkboxes.length) {
    if (checkboxes[j].checked) checkboxesValid = true;
    j++;
}

if (!checkboxesValid) {
    document.getElementById('checkboxerror').innerHTML = "(Please select at least one)";
    formValid = false;
} else {
    document.getElementById('checkboxerror').innerHTML = "";

}
// now that all validations have run, return the conclusion
if (counter === 0) {
    alert("Congrats");
}

}

Ok. I gave that a shot, and I moving the callback function from above of the validate function down to below the validate function. Neither way worked. This is a big struggle for me. Where to put functions in the code to achieve the desired outcome. Putting the callback above and below both gave me the same results. The page runs and validates afterwards. You are being very helpful, and I am extremely grateful. Thank you for the big explanation of how it works. Understanding this is the only way I will learn. But here is my updated code....I put the counter variable at the top so it can be used inside of both the validate function and the callback function. (if that is wrong, tell me) I also added the counter increment inside of each "if" statement. I almost feel like the radio and checkboxes are now throwing this off. (tell me i am wrong lol) I am just trying to have open dialogue on how my brain is processing this.

Thank you for your patience and time.

let counter = 0;

function validate(formValid, checkCounter) {

// NEW: move this way up here so all validations can affect its value:
var formValid = true;
if (!formValid) {
    counter++;
}
// function to check if a name has been entered
var name = document.getElementById('name').value;

if (name == null || name.trim() == "") {
    document.getElementById('nameerror').innerHTML = "Please enter your full name";
    counter++;
} else {
    document.getElementById('nameerror').innerHTML = "";
}

// function to check if an email has been entered
var email = document.getElementById('email').value;

if (email == null || email.trim() == "") {
    document.getElementById('emailerror').innerHTML = "Please enter your email address";
    counter++;
} else {
    document.getElementById('emailerror').innerHTML = "";
}

// function to check if a telephone number has been provided
var phone = document.getElementById('phone').value;

if (phone == null || phone.trim() == "") {
    document.getElementById('phoneerror').innerHTML = "Please enter your telephone number";
    counter++;
} else {
    document.getElementById('phoneerror').innerHTML = "";
}

//validate the select options
var select = document.getElementById('select').value;
    if (select == '') {
        document.getElementById('selecterror').innerHTML = "Please make a selection";
        counter++;
    } else {
        document.getElementById('selecterror').innerHTML = "";

    }



//function to validate the textarea field
var name = document.getElementById('textarea').value;

if (name == null || name.trim() == "") {
    document.getElementById('textareaerror').innerHTML = "Please enter additional info";
    counter++;
} else {
    document.getElementById('textareaerror').innerHTML = "";
}
// function to validate if any radio button has been selected
var radios = document.getElementsByName('radio');
var radiosValid = false;
var i = 0;

while (!radiosValid && i < radios.length) {
    if (radios[i].checked) radiosValid = true;
    i++;
}

if (!radiosValid) {
    document.getElementById('radioerror').innerHTML = "(Please check one)";
    counter++;
} else {
    document.getElementById('radioerror').innerHTML = "";
}

// function to confirm if any checkbox has been checked
var checkboxes = document.getElementsByName('checkbox');
var checkboxesValid = false;
var j = 0;

while (!checkboxesValid && j < checkboxes.length) {
    if (checkboxes[j].checked) checkboxesValid = true;
    j++;
}

if (!checkboxesValid) {
    document.getElementById('checkboxerror').innerHTML = "(Please select at least one)";
    counter++;
} else {
    document.getElementById('checkboxerror').innerHTML = "";

}

checkCounter(counter);

}

function checkCounter(counter) { if(counter === 0){ alert("Your form has been submitted"); } }

If its possible can you post your html code? So i can replicate it. Also i would keep the counter variable as var and inside the validate function at the top like you had it before. Also try defining the checkCounter function at the top before validate.

here is the HTML for the form

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Contact Us</title> <style>

    .contact-header {
        font-family: cursive;
        text-align: center;
        font-size: 50px;
        color: darkred;
    }

    form {
        font-weight: bold;
        text-align: center;
    }


    .contact {
        font-weight: normal;
    }
    .checkbox input {
        margin: 0 10px 0;
    }

    textarea {
        width: 20%;
        height: 5rem;
    }

    .sendRequest {
        text-align: center;
    }

</style>
<!--link to bootstrap css-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!--link for icons-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

<!--link to external stylesheet-->
<link href="restaurantStyles.css" rel="stylesheet" type="text/css" />

</head> <body> <div class="container"> <header> <div class="jumbotron name-font"> <h1 class="display-4">Dan's Cakes</h1> <hr class="my-4"> <p class="lead">BIG NEWS!! Dan's Cakes will be opening a new restaurant VERY soon!!!!</p>

        </div>
    </header>
    <hr />
    <nav>
        <!--home icon link-->
        <a href="index.html" class="btn badge-pill"><i class="fas fa-home"></i></a>
        <a href="menu.html" class="btn badge-pill">Menu</a>
        <a href="contact.html" class="btn badge-pill">Contact Us</a>
    </nav>
    <hr />
    <h2 class="contact-header">Contact Us</h2>
    <hr />

    <!--form for contact info-->
    <form name="contactForm" method="post" id="contactForm" novalidate onsubmit="return validate()">
        <div class="form-group col-form-label">
            <label for="name">Name: </label>
            <input type="text" class="form-control" id="name" placeholder="Please enter your full name.." required>
            <span id="nameerror" class="hint"></span>

        </div>
        <div class="form-group">
            <label for="email">Email: </label>
            <i class="fas fa-envelope prefix"></i>
            <input type="email" class="form-control" id="email" placeholder="Please enter your email address.." aria-describedby="email" required>
            <span id="emailerror" class="hint"></span>
            <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>

        </div>
        <div class="form-group">
            <label for="phone">Phone: </label>
            <i class="fas fa-phone-square"></i>
            <input type="tel" class="form-control" id="phone" required>
            <span id="phoneerror" class="hint"></span>


        </div>
        <!--select menu-->
        <label for="reason-select">Reason For Inquiry:</label>
        <select id="select" name="reason" class="custom-select" required>
            <option value="">--Please Choose an Option--</option>
            <option value="catering">Catering</option>
            <option value="private">Private Party</option>
            <option value="feedback">Feedback</option>
            <option value="other">Other</option>
        </select>
        <span id="selecterror" class="hint"></span>

        <br />
        <br />
        <!--text area for additional info-->
        <div class="form-group">
            <label for="info">Additional Information: </label>
            <textarea class="form-control" id="textarea" rows="5"></textarea>
            <span id="textareaerror" class="hint"></span>
        </div>

        <!--radio buttons for visiting restaurant-->
        <label for="radio">Have you been to the restaurant?</label>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="radio" id="no-radio" value="no">
            <label class="form-check-label" for="no-radio">
                No
            </label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="radio" id="yes-radio" value="yes">
            <label class="form-check-label" for="yes-radio">
                Yes
            </label>
            <span id="radioerror" class="hint"></span>
        </div>
        <br />
        <!--checkboxes for contacting-->
        <label for="checkboxes">Best days to contact you:</label>
        <div id="checkboxlist">
        <div class="form-check form-check-inline">
            <input class="form-check-input" name="checkbox" type="checkbox" id="monday" value="monday">
            <label class="form-check-label" for="monday">M</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" name="checkbox" type="checkbox" id="tuesday" value="tuesday">
            <label class="form-check-label" for="tuesday">T</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" name="checkbox" type="checkbox" id="wednesday" value="wednesday">
            <label class="form-check-label" for="wednesday">W</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" name="checkbox" type="checkbox" id="thursday" value="thursday">
            <label class="form-check-label" for="thursday">Th</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" name="checkbox" type="checkbox" id="friday" value="friday">
            <label class="form-check-label" for="friday">F</label>
        </div>
        <span id="checkboxerror" class="hint"></span>
        </div>

        <!--send request button-->
        <div class="sendRequest" id="contact-submit">
            <input type="submit" value="Send Request">
        </div>
    </form>
    <br />

    <br />
    <footer>
        <p>1123 Silk Way, Anchorage, AK, 99501</p>
        <p>907-998-0122</p>
    </footer>
</div>
<script>
    document.contactForm.name.onfocus = function () {
        document.getElementById('namehint').innerHTML = "(Enter full name)";
    }

</script>
<!--scripts for jquery, popper, and bootstrap-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<!--javascript link to external sheet-->
<script src="validate.js"></script>

<!--<script>
    document.contactForm.name.onfocus = function () {
        document.getElementById('namehint').innerHTML = "(Enter full name)";
    }

</script>
    -->

</body> </html>

Thank you so much Emmanuel!! That worked like a charm! The only thing I am seeing now is after the submit, the page doesn't refresh with a blank form. I will be working on this problem now.

If you have a PayPal, post it because I would love to send you some money for all of your help. You have done so much explaining and taking time out of your day to help me.

Thank you again!!

This is a website I am building as part of pre-requirements for a bootcamp I will be starting in April.

Thank you for all of your help and explanations.