I was doing a project series on CodeCademy and I got a project in the series to do a client side form validation using JavaScript/jQuery.
My HTML is:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<link rel='stylesheet' href='stylesheet.css' type='text/css'/>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<form>
First Name : <input type='text' id='fname' placeholder='Enter First Name'><br><br>
Last Name : <input type='text' id='lname' placeholder='Enter Last Name'><br><br>
Age : <input type='text' id='age' placeholder='Age'><br><br>
Sex : <input type='radio' class='sex'> Male <input type='radio' class='sex'> Female
</form>
<button id='submit'>Submit</button>
</body>
</html>
My JavaScript/jQuery is:
$(document).ready(function()
{
var fname = document.getElementById('fname').val();
var lname = document.getElementById('lname').val();
var age = document.getElementById('age').val();
/*Do not know how to get element by class and that too, two different type. Have to check if user chose anything or not*/
$("#submit").click(function()
{
if(fname.length === 0)
{
alert("Please input a first name");
}
else if(lname.length === 0)
{
alert("Please input a last name");
}
else if(age.length === 0)
{
alert("Please input an age");
}
});
});
I don't need a very complicated code and please help me in the HTML department if something is wrong there or if something needs to be added there.
Also, I don't know how to get different elements in a class. I have put a comment in my jQuery regarding that so please help if you can.
This is a problem in a CodeCademy project and this is where a lot of newbies in JS and jQuery have a problem, so if you can help, it'll help a lot of people and not just me.
Thanks!
You need to use .value instead of .val() since you're using pure Javascript:
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;
if you want to use .val() method then you need a jQuery object:
var fname = $('#fname').val();
var lname = $('#lname').val();
var age = $('#age').val();
You also need to put those variables inside .click() handler in order to get the updated value of these textboxes, currently you only retrieve the value on page load which is always equal to 0:
$(document).ready(function () {
$("#submit").click(function () {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;
if (fname.length == 0) {
alert("Please input a first name");
} else if (lname.length == 0) {
alert("Please input a last name");
} else if (age.length == 0) {
alert("Please input an age");
}
});
});
Fiddle Demo
from your example, get elements by class name
var lists = document.getElementsByClassName("sex");
to access specific value use lists[0].value it will return "Male" or lists[1].value will return "Female"
if you use native/pure javascript use .value not val() . val() is only for jquery
It looks like you're asking a couple questions at once.
As suzonraj, pointed out you need document.getElementsByClass to get elements by class name and as Felix pointed out, you need to place your data look up inside your .click event in order to get the current, not page .ready value.
I will add that you should add the name parameter to your radio boxes, so they actually function like radio boxes - turning one off when another is clicked. With this, you could use document.getElementsByName, which is really what you're after with a radio collection.
As far as validation, you would then need to go through your array of elements by name or class, and then validate that at least one is .checked.
Here is an example based off the code Felix shared: http://jsfiddle.net/5zqW7/8/
One addition, is that validation occurs for all elements rather than just until the first element that fails. This is a little more communicative to the user, as it will identify all the wrong fields, not just the first, hit submit, then the second, and so on. In a real form, you'd probably have something less loud than an alert() anyhow. That may not be necessary for your assignment.
Here is very simple way to make form validation using jquery
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='registration']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
firstname: "required",
lastname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: {
required: "Please provide a valid user name",
email: "Please enter a valid email address"
}
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
#import url("https://fonts.googleapis.com/css?family=Open+Sans");
/* Styles */
* {
margin: 0;
padding: 0;
}
body {
font-family: "Open Sans";
font-size: 14px;
}
.container {
width: 500px;
margin: 25px auto;
}
form {
padding: 20px;
background: #2c3e50;
color: #fff;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
form label,
form input,
form button {
border: 0;
margin-bottom: 3px;
display: block;
width: 100%;
}
form input {
height: 25px;
line-height: 25px;
background: #fff;
color: #000;
padding: 0 6px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
form button {
height: 30px;
line-height: 30px;
background: #e67e22;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
label.error {
color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js'></script>
<div class="container">
<h2>Registration</h2>
<form action="" name="registration">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="john#doe.com" />
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="●●●●●" />
<button type="submit">Register</button>
</form>
</div>
function validate() {
var scheduledOn = $("#ScheduledOn").val();
var status = $(".Status option:selected").text();
var result = true;
if (id == "") {
var scheduledOn = $("#ScheduledOn").val();
var category = $(".categoryList option:selected").text();
var activityTask = $(".activityTaskList option:selected").text();
var lead = $("#LeadID").val();
var agent = $("#AgentID").val();
if (category == "Select Category") {
$("#categoryValidation").show();
$("#categoryValidation").text("The Category field is required");
}
else {
$("#categoryValidation").hide();
}
if (category == "Agent Recruitment" || category == "Direct Sales" || category == "Joint Field Work" || category == "Select Category" || category == "Agent Development") {
var activityTask = $(".activityTaskList option:selected").text();
if (activityTask == "Select Activity Task") {
$("#activityTaskValidation").show();
$("#activityTaskValidation").text("The Activity Task field is required");
}
else {
$("#activityTaskValidation").hide();
}
}
if (category == "Joint Field Work") {
if (agent == "" || agent == "Select Agent") {
$("#agentValidation").show();
$("#agentValidation").text("The Agent field is required");
result = false;
}
else {
$("#agentValidation").hide();
}
}
if (category == "Joint Field Work") {
if (lead == "" || lead == null || lead == "Select Lead") {
$("#leadValidation").show();
$("#leadValidation").text("The Lead field is required");
result = false;
}
else {
$("#leadValidation").hide();
}
}
if (category == "Agent Recruitment" || category == "Agent Development") {
if (agent == "" || agent == "Select Agent") {
$("#agentValidation").show();
$("#agentValidation").text("The Agent field is required");
result = false;
}
else {
$("#agentValidation").hide();
}
}
if (category == "Direct Sales") {
if (lead == "" || lead == "Select Lead" || lead == null) {
$("#leadValidation").show();
$("#leadValidation").text("The Lead field is required");
result = false;
}
else {
$("#leadValidation").hide();
}
}
if (scheduledOn == "" || scheduledOn == null) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field is required");
result = false;
}
else if (Date.parse(scheduledOn) <= Date.now()) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
result = false;
}
else {
$("#scheduledOnValidation").hide();
}
return result;
}
else {
var scheduledOn = $("#NewScheduledOn").val();
var status = $(".Status option:selected").text();
if (document.getElementById("SetAppointment_Y").checked) {
var activityTask = $(".activityTaskList").val();
if (activityTask == null || activityTask == "") {
$("#activityTaskValidation").show();
$("#activityTaskValidation").text("The Activity Task field is required");
result = false;
}
else {
$("#activityTaskValidation").hide();
$("#scheduledOnValidation").hide();
}
if (status != null && (scheduledOn == "" || scheduledOn == null)) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field is required");
$("#statusValidation").hide();
result = false;
}
else if (Date.parse(scheduledOn) <= Date.now()) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
result = false;
}
else {
$("#scheduledOnValidation").hide();
$("#statusValidation").show();
}
}
}
return result;
}
Related
guys I'm new here and it's my first time posting . been learning html / CSS / javascript since 5 months ago and now I'm trying to build a very simple contact form where if there's no value it will show error icon + message error blow the input , been trying to figure it out for like 12h+ but nothing i saw in stack worked ....... already have the solution of a guy , he used javascript to manipulate the style and add and remove the error using css , but i want to do it the other way around with manipulating the DOM with JAVA using document.query Selector
let firstname = document.querySelector("#inputfirst").value;
let form = document.querySelector('#loginform')
//form.addEventListener('submit', (e) => {
// e.preventDefault();})
function validation() {
if (firstname == "" || firstname == null || firstname == " ") {
document.querySelector("#inputfirst").classList.add("firstname")
document.querySelector("#firstname_Error").innerHTML = "firstname"
return false;
}
else {
document.querySelector("#inputfirst").classList.remove("firstname")
document.querySelector("#firstname_Error").innerHTML = ""
}
}
/**testing for 1st input only **/
.firstname {
background-image: url(./images/icon-error.svg);
background-position: 24rem 13px;
background-repeat: no-repeat;
border: 1px solid rgb(247, 10, 10);
}
<form novalidate id="loginform" name="loginform" onsubmit="return validation()"; >
<input id="inputfirst" name="firstname" type="text" placeholder="First Name" class="button-shap" required >
<span id="firstname_Error"></span>
</form>
Get the value of the element inside the function.
Everything else seems to be working.
Here is the edited code.
let firstnameElement = document.querySelector("#inputfirst");
let form = document.querySelector('#loginform')
//form.addEventListener('submit', (e) => {
// e.preventDefault();})
function validation() {
let firstname = firstnameElement.value
if (firstname == "" || firstname == null || firstname == " ") {
document.querySelector("#inputfirst").classList.add("firstname")
document.querySelector("#firstname_Error").innerHTML = "firstname"
return false;
}
else {
document.querySelector("#inputfirst").classList.remove("firstname")
document.querySelector("#firstname_Error").innerHTML = ""
}
}
Also if your javascript file is linked at the head of the html make sure to add the defer attribute so it loads after the document.
<script src="test.js" defer></script>
I am trying to create a form with some basic client side validation. In the form i have 3 input fields for, username, email and password. Initially they have a common class that is input. Also i attached a sibling paragraph element to these input elements, these paragraph element contains some input specification that has to be displayed to user if user enters something invalid.
In CSS i have basically created two classes, valid and invalid, valid just turns the border of input elements to green, and invalid turns border to red and sets the paragraph element opacity to 1 from 0(initial style).
In script file to check validity of user's input i have three boolean variables, isUserNameValid, isEmailValid, isPasswordValid, all these three are initially set to false.
Now i am adding these CSS classes during runtime as user inputs. Adding classes (valid and invalid) is working fine for first input element that is username input element, but as soon as i go to next input element that is email and type a single letter, script is adding class valid to email input element instead of invalid, even though isEmailValid is false.
I tried my best to figure out why it's adding class valid even though i am explicitly saying if the isEmailValid is equals to false add a class of invalid and remove class valid, instead it's doing the opposite.
I have attached the fiddle link, also i am not very much experienced in JavaScript, so, explanation in simple English is appreciated.
if(username.length > 5) {
isUserNameValid = true
}
if(email.length > 10) {
isEmailValid = true
}
if(password.length > 10) {
isPasswordValid = true
}
if(isUserNameValid === true && isEmailValid === true && isPasswordValid === true) {
loginButton.disabled = false
loginButton.style.cursor = 'pointer'
} else {
console.log('username',username, isUserNameValid)
console.log('email',email, isEmailValid)
console.log('password',password, isPasswordValid)
loginButton.disabled = true
loginButton.style.cursor = 'default'
if(isUserNameValid === false) {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if(isEmailValid === false) {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if(isPasswordValid === false) {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if(isUserNameValid === true) {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
if(isEmailValid === true) {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
if(isPasswordValid === true) {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
}
FIDDLE LINK: https://jsfiddle.net/weg9jy0c/5/
will this work for you?
https://jsfiddle.net/gnca42xp/1/
const form = document.querySelector('.main-form')
form.addEventListener('keyup', (e) => {
const loginButton = document.querySelector('.login-btn')
const username = document.querySelector('#name').value
const email = document.querySelector('#email').value
const password = document.querySelector('#password').value
let isUserNameValid = false;
let isEmailValid = false;
let isPasswordValid = false;
currentUpdateField = e.target.getAttribute('id');
if (username.length > 5) {
isUserNameValid = true
}
if (email.length > 10) {
isEmailValid = true
}
if (password.length > 10) {
isPasswordValid = true
}
if (isUserNameValid === true && isEmailValid === true && isPasswordValid === true) {
e.target.classList.remove('invalid')
loginButton.disabled = false
loginButton.style.cursor = 'pointer'
} else {
console.log('username', username, isUserNameValid)
console.log('email', email, isEmailValid)
console.log('password', password, isPasswordValid)
loginButton.disabled = true
loginButton.style.cursor = 'default'
if (isUserNameValid === false && currentUpdateField === 'name') {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if (isEmailValid === false && currentUpdateField === 'email') {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if (isPasswordValid === false && currentUpdateField === 'password') {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if (isUserNameValid === true && currentUpdateField === 'name') {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
if (isEmailValid === true && currentUpdateField === 'email') {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
if (isPasswordValid === true && currentUpdateField === 'password') {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
}
})
.input {
outline: none;
}
.valid {
border: 1px solid rgb(89, 224, 89);
}
input+p {
opacity: 0;
}
.invalid {
border: 2px solid rgb(245, 101, 101);
}
input.invalid+p {
opacity: 1;
color: orange;
}
<html>
<title>Demo Form</title>
<body>
<form class="main-form" method="post">
<input class="input" type="text" name="username" id="name" placeholder="Username">
<p>Username must have more than 5 characters</p>
<input class="input" type="email" name="email" id="email" placeholder="Email">
<p>Email must of format <b>email#site.domain</b></p>
<input class="input" type="password" name="password" id="password" placeholder="Password">
<p>Password must have more than 5 characters and aplhanumeric with a special character</p><br>
<button type="submit" class="login-btn" disabled>Register</button>
</form>
</body>
</html>
What happens in your case
1) First user enters data in username it is valid after 5 characters
2) then user enters data in email field, here e.target is email field, but as from your code, isUsernameInvalid is defined false, and added class to e.target which is email field.
That is why your code is not working
So what i have done is,
I am getting id on the current updating field, and then adding or removing classes only if id matches
I'm trying to create a website for learning/exercise but I'm stuck at user registration validation. There's no error message and nothing happens.
Here is a JsFiddle Link.
Also I tried:
if(user_name.length < 3 && user_name!=="")
and
if(user_name.length < 3)
Code snippet:
var user_name = $('#username').val();
$('#username').on('keyup',function(){
if(user_name.length < 3 && user_name!=""){
$('#username-info').html('Username must be at least 3 characters.');
}
else if(user_name.length > 3){
$('#username_info').html('No problem');
}
});
#username-info {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info"></p>
The keyup functions need to trigger on the input field.
The keyup functions updates the username (else it will be the same).
$('#username').on('keyup',function(){
var user_name = $('#username').val();
if(user_name.length < 3 && user_name!=""){
$('#username-info').html('Username must be at least 3 characters.');
}
else if(user_name.length >= 3){
$('#username-info').html('No problem');
}
});
I think you have just put wrong ids AND your variable user_name is only initialized one time on start, so its value is always empty.
$('#username').on('keyup', function() {
var user_name = $(this).val();
if (user_name.length < 3 && user_name != "") {
$('#username-info').html('Username must be at least 3 characters.');
} else if (user_name.length > 3) {
$('#username-info').html('No problem');
}
});
#username-info {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info">
</p>
I use your code as reference and made some changes in it for better output.
You can try this, here i am changing color code as well for the error message so you will get better result.
$('#username').on('keyup',function(){
var user_name = $('#username').val();
if(user_name.length < 3 && user_name != ""){
$('#username-info').html('Username must be at least 3 characters.');
$('#username-info').addClass('username-info');
$('#username-info').removeClass('username-info-2');
}
else if(user_name.length >= 3){
$('#username-info').html('No problem');
$('#username-info').addClass('username-info-2');
$('#username-info').removeClass('username-info');
}
});
.username-info {
color: red;
}
.username-info-2 {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info"></p>
Currently, user_name is declared once at the start of your script, so it will never be updated.
Then, you attached a keyup event handler on <p#username-info>, not <input#username>, so when you input something into it, nothing will be triggered.
So, you need to update user_name at each input into <input#username>.
// Here, you need to attach the event handler of #username, not #username-info.
$('#username').on('keyup', function() {
// And here, you get the value of your input.
let user_name = $('#username').val();
// let user_name = $(this).val(); works too.
// Writing "(user_name)" in a condition is the same as "(user_name !== '')".
if (user_name && user_name.length < 3) {
$('#username-info').html('Username must be at least 3 characters.');
} else if (user_name.length >= 3) {
// You wrote "#username_info" instead of "#username-info" here.
$('#username-info').html('No problem');
}
});
#username-info {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info">
</p>
you have a lot of typos in your script and you looked for the paragraph on key up not your input field.
var user_name = "";
$('#username').on('keyup',function(){
user_name = $('#username').val();
if(user_name.length <= 3 && user_name!=""){
$('#username-info').html('Username must be at least 3 characters.');
}
else if(user_name.length > 3){
$('#username-info').html('No problem');
}
});
The code is not working the way I want it to.
I wrote this code to display an alert if either login or password field is not filled. But if I fill the login info and skip password, it doesn't show alert message as planned. Any help will be appreciated.
function check() {
var x = document.forms['myform']['lid'].value;
if (x == "") {
alert("Please Enter the Login-Id")
y = document.forms['myform']['pass'].value;
if (y == "") {
alert("The password field can't be blank")
}
}
}
body {
background-color: lightblue;
margin-left: 100px;
margin-right: 100px;
}
<center>
<h1> Welcome to X-mail.com </h1><br><br><br>
<form name='myform'>
Login-Id<input type="text" name='lid'> </input><br><br> Password
<input type='password' name='pass'> </input><br><br><br>
<button onclick="check()"> Login</button>
</form>
Don't have an account?
Sign-Up
</center>
You just have your two checks nested in one another. They need to be separate like this:
function check() {
var x = document.forms['myform']['lid'].value;
if (x == "") {
alert("Please Enter the Login-Id")
}
y = document.forms['myform']['pass'].value;
if (y == "") {
alert("The password field can't be blank")
}
}
Ideally, you want to check if both are missing and only show a single alert but I will leave that up to you to figure out.
Your check function logic seems to be nested and that's the issue. The correct logic needs to be
function check() {
var x = document.forms['myform']['lid'].value;
if (x == "") {
alert("Please Enter the Login-Id")
}
y = document.forms['myform']['pass'].value;
if (y == "") {
alert("The password field can't be blank")
}
}
You're missing a closed bracket after your first if statement.
if (x==""){
alert("Please Enter the Login-Id")
} // make sure you close your bracket here
y=document.forms['myform']['pass'].value;
... rest of your code ...
If you do that and have two ifs, you should be good to go.
The problem is that the validation for the pass field will only occur if the lid field is equal to "". Move the validation for the pass field outside of the validation for the login-id field.
function check() {
var x = document.forms['myform']['lid'].value;
if (x == "") {
alert("Please Enter the Login-Id")
}
y = document.forms['myform']['pass'].value;
if (y == "") {
alert("The password field can't be blank")
}
}
body {
background-color: lightblue;
margin-left: 100px;
margin-right: 100px;
}
<center>
<h1> Welcome to X-mail.com </h1><br><br><br>
<form name='myform'>
Login-Id<input type="text" name='lid'> </input><br><br> Password
<input type='password' name='pass'> </input><br><br><br>
<button onclick="check()"> Login</button>
</form>
Don't have an account?
Sign-Up
</center>
Additionally you may want to pass in the event Object into the function to prevent the default action (submitting the form) with event.preventDefault() if the validation does not pass.
function check(e) {
var x = document.forms['myform']['lid'].value;
if (x == "") {
alert("Please Enter the Login-Id");
e.preventDefault();
}
y = document.forms['myform']['pass'].value;
if (y == "") {
alert("The password field can't be blank");
e.preventDefault();
}
}
body {
background-color: lightblue;
margin-left: 100px;
margin-right: 100px;
}
<center>
<h1> Welcome to X-mail.com </h1><br><br><br>
<form name='myform'>
Login-Id<input type="text" name='lid'> </input><br><br> Password
<input type='password' name='pass'> </input><br><br><br>
<button onclick="check(event)"> Login</button>
</form>
Don't have an account?
Sign-Up
</center>
I am making a contact form, which includes name, email and a message which can then be submitted. If any of the three fields are null an error message is shown which I have working. The word "error" appears in all three field boxes. My issue is that I am trying to add a single error message which will be hidden and only appear if an error is made, this will say "Please fill in all fields before submitting"
I am new to ColdFusion and mixing HTML with JavaScript. So I was wondering if anyone could please give me some tips as to what I have done wrong. I have tried to manipulate it many ways and tried adding a div for this message in my CSS. But to no avail, the message always shows up. It doesn't stay hidden when needed.
I would really appreciate any information or help anyone could give, I am so confused and have searched the whole web looking for this info.
Here is my code:
var requiredFields = ["name", "email", "message"];
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "Error";
var emptyFields = true;
}
}
if (!emptyFields) {
myForm.submit();
} else {
if (document.getElementById("name == null || email == null || message == null")
document.getElementById("errormessage").style.visibility = "visible";
} else {
document.getElementById("errormessage").style.visibility = "hidden";
}
}
function resetField(myField) {
if (myField.value == "Error") {
myField.style.color = "#000";
myField.value = "";
}
}
function resetForm(myForm) {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
myForm[fieldName].style.color = "#000";
}
}
and here is the CSS for my error message:
#errormessage {
font-style: italic;
text-indent: 10px;
border: dotted;
border-width: 1px;
}
There is a much easier way to do form validation with ColdFusion. If you use <cfform> and <cfinput> tags then a lot of JavaScript is written for you. All you have to do is something like this:
<cfform action="whereever">
<cfinput type="text" name="fred" required="yes" message="fred is required">
<input type="submit">
</cfform>
It's not as fancy as what you are attempting, but it's simple and it's effective.
Please go through the below code and see what you have done wrong.
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body onload="checkContactForm();">
<style type="text/css">
#errormessage {
font-style: italic;
text-indent: 10px;
border: dotted;
border-width: 1px;
}
</style>
<script type="text/javascript">
var requiredFields = ["name", "email", "message"];
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "Error";
var emptyFields = true;
}
}
if (!emptyFields) {
myForm.submit();
}
else
{
if (emptyFields) {
document.getElementById("errormessage").innerHTML = "Validation Error";
document.getElementById("errormessage").style.visibility = "visible";
}
else
{
document.getElementById("errormessage").style.visibility = "hidden";
}
}
}
function resetField(myField) {
if (myField.value == "Error") {
myField.style.color = "#000";
myField.value = "";
}
}
function resetForm(myForm) {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
myForm[fieldName].style.color = "#000";
}
}
</script>
<div id="errormessage"></div>
<form action="STO1.html" method="POST" name="myForm">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
<input type="text" name="message" id="message"/>
<input type="submit"/>
</form>
</body>
</html>