Solved

Javascript Form Validation. how to remove error when focused on a input field using onfocus

Posted on 2013-11-08
3
575 Views
Last Modified: 2013-11-11
currently when you submit the form any field that is left black receives an error message. The field also turns red with a red border showing the user that they forgot to put data in the box. Also the label turns from black to red.

What i need is for when the user focuses on a box(using onfocus) the code will change the color of the field label back to regular black and remove the red box around the field indicting that the user has corrected the error.

index.htm:

<form name="myForm">

        <legend>Customer Information</legend>

    <fieldset id="custInfo">

        <article id="errorFName"></article>
        <article id="errorLName"></article>
        <article id="errorAddress"></article>
        <article id="errorCity"></article>
        <article id="errorState"></article>
        <article id="errorZip"></article>
        <article id="errorUsername"></article>
        <article id="errorPassword"></article>
        <article id="errorAgreement"></article>
        <article id="passwordMatchMessage"></article>


        <label id="firstNameLabel" for="firstName">First Name:</label>
        <input type="text" name="firstName" id="firstName" />


        <label type="text" for="middleInitial">Middle Initial:</label>
        <input name="middleInitial" id="middleInitial" size="2" />

        <label id="lastNameLabel" for="lastName">Last Name:</label>
        <input type="text" name="lastName" id="lastName" 
               placeholder="Last Name"/>


        <label id="streetAddressLabel" for="streetAddress">Street Address:</label>
        <input name="streetAddress" id="streetAddress" />


        <label id="cityLabel" for="city">City:</label>
        <input type="text" name="city" id="city" placeholder="Tulsa"/>


        <label id="stateLabel" for="state">State:</label>
        <input type="text" name="state" id="state" placeholder="OK"/>


        <label id="zipLabel" for="zip">Zip Code:</label>
        <input name="zip" id="zip" 
               placeholder="xxxxx (-xxxx)"/>


        <label id="usernameLabel" for="username">Username:</label>
        <input name="username" id="username" 
               placeholder="username"/>


        <label id="passwordLabel" for="password">Password:</label>
        <input type="password" name="password" id="password" 
               placeholder="password"/>


        <label id="confirmPasswordLabel" for="confirmPassword">Password Confirmation:</label>
        <input type="password" name="confirmPassword" id="confirmPassword" onkeyup="passwordMatch(); return false;"/>


        <label id="userAgreement">
        <input type="checkbox" name="userAgreement" id="userAgreement" />

        By clicking the checkbox, you agree to our Terms and that you have read our <a href="#">Data Use Policy</a>, including our <a href="#">Cookie Use</a>.
        </label>  
        <p>
            <button id="submitButton" onclick="return validateForm();">Submit</button>
            <button id="resetButton">Reset</button>

        </p>

    </fieldset>


    </form>

Open in new window


style.css

/* Styles for Fieldset*/

body {
background: #E8E8E8 ;
}

form {
width: 500px;
margin: 50px;
}

fieldset#custInfo {
background-color: #99ccff;
border: 2px solid #0066ff;

}

legend {
background-color: #0066ff;
color: white;
padding: 10px 0px;
text-indent: 10px;
width: 100%;
}



/*Styles for labels*/

label{
clear: left;
display: block;
float: left;
font-size: 0.9em;
margin: 13px 4% 7px 5px;
width: 150px;
}

label#userAgreement {
margin: auto;
width: 100%;
font-size: 0.8em;
}
/*Styles for input*/

input {
display: block;
float: left;
font-size: 0.9em;
height: 25px;
margin: 7px 0px;
width: 250px;

}

input#userAgreement {
width: 15px;
margin: auto 5px;
}

/*style for Buttons*/


button {
display: block;
float: left;
height: 40px;
width: 200px;
margin: 0px 11px;
}



article {
display: block;
font-size: 0.9em;
color: red;
margin: 7px 10px;


}

Open in new window


validation.js

function validateForm() {

var firstName = document.getElementById('firstName');
var firstNameLabel = document.getElementById('firstNameLabel')
var lastName = document.getElementById('lastName')
var lastNameLabel = document.getElementById('lastNameLabel')

if( firstName.value == "" )
{
        firstName.style.border = "1px solid red";
        firstName.style.backgroundColor = "#FFCCCC";
        firstNameLabel.style.color = "red";
        errorFName.innerHTML = 'First Name cannot be left blank!';

}



if( document.getElementById('lastName').value == "" )
{
        lastName.style.border = "1px solid red";
        lastName.style.backgroundColor = "#FFCCCC";
        lastNameLabel.style.color = "red";
        errorLName.innerHTML = 'Last Name cannot be left blank!';

}

if( document.getElementById('streetAddress').value == "" )
{
        document.getElementById('streetAddress').style.border = "1px solid red";
        document.getElementById('streetAddress').style.backgroundColor = "#FFCCCC";
        document.getElementById('streetAddressLabel').style.color = "red";
        errorAddress.innerHTML = 'Address cannot be left blank!';

}

if( document.getElementById('city').value == "" )
{
        document.getElementById('city').style.border = "1px solid red";
        document.getElementById('city').style.backgroundColor = "#FFCCCC";
        document.getElementById('cityLabel').style.color = "red";
        errorCity.innerHTML = 'City cannot be left blank!';

}

if( document.getElementById('state').value == "" )
{
        document.getElementById('state').style.border = "1px solid red";
        document.getElementById('state').style.backgroundColor = "#FFCCCC";
        document.getElementById('stateLabel').style.color = "red";
        errorState.innerHTML = 'State cannot be left blank!';

}

if( document.getElementById('zip').value == "" )
{
        document.getElementById('zip').style.border = "1px solid red";
        document.getElementById('zip').style.backgroundColor = "#FFCCCC";
        document.getElementById('zipLabel').style.color = "red";
        errorZip.innerHTML = 'Zip Code cannot be left blank!';

}

if( document.getElementById('username').value == "" )
{
        document.getElementById('username').style.border = "1px solid red";
        document.getElementById('username').style.backgroundColor = "#FFCCCC";
        document.getElementById('usernameLabel').style.color = "red";
        errorUsername.innerHTML = 'Username cannot be left blank!';

}
if( document.getElementById('password').value == "" )
{
        document.getElementById('password').style.border = "1px solid red";
        document.getElementById('password').style.backgroundColor = "#FFCCCC";
        document.getElementById('passwordLabel').style.color = "red";
        errorPassword.innerHTML = 'The Password cannot be left blank!';

}

if( document.myForm.confirmPassword.value == "") 
{
        document.getElementById('confirmPassword').style.border = "1px solid red";
        document.getElementById('confirmPassword').style.backgroundColor = "#FFCCCC";
        document.getElementById('confirmPasswordLabel').style.color = "red";
}

if( document.myForm.userAgreement.checked == false)
{
    document.getElementById('userAgreement').style.color = "red";
    errorAgreement.innerHTML = 'You must agree to our User Agreement by checking the Box!'
}



return false;

}        


function passwordMatch() {
var password = document.getElementById('password');
var confirmPassword = document.getElementById('confirmPassword');
var message = document.getElementById('passwordMatchMessage');


if(password.value == confirmPassword.value){
    myForm.confirmPassword.style.backgroundColor = "#66CC66";
    message.innerHTML = 'Passwords Match!';
}

else {
    myForm.confirmPassword.style.backgroundColor = "#FFCCCC";
    message.innerHTML = 'Passwords Do Not Match!';
}
return false;

}

Open in new window

0
Comment
Question by:djphillovesyou
  • 2
3 Comments
 
LVL 58

Assisted Solution

by:Gary
Gary earned 500 total points
ID: 39634021
Are you using jQuery? Since you included it in your fiddle.  If so just add

$("form input").focus(function(){
    $(this).css("border","1px solid black")  
})
0
 

Author Comment

by:djphillovesyou
ID: 39634117
Unfortunately I haven't really studied jQuery so i would prefer not to use it.
0
 
LVL 58

Accepted Solution

by:
Gary earned 500 total points
ID: 39634187
Use this then:

var inputs = document.getElementsByTagName('input')
for (var i = 0; i < inputs.length; i++){
	inputs[i].onfocus = function() { 
		this.style.border='1px solid #000';
	} 
}

Open in new window


p.s.
jQuery is very easy to use and makes writing javascript functions a whole lot simpler. Setting bindings, onclicks etc is done in with a short snippet of code.  If you know javascript then you already know jquery (almost) since jQuery is just a wrapper framework for javasript
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now