Reputation: 666
I am trying to make a function for text input validation and its not working.
JavaScript:
function validateText(id)
{
var x=document.forms["myForm"][id].value;
if (x==null || x=="")
{
var text = id+"Text";
document.getElementById(text).style.visibility ="visible";
}else {
var text = id+"Text";
document.getElementById(text).style.visibility="hidden";
}
}
Html:
<label for="familyName">Family name</label>
<input type="text" id="familyName" id="familyName" onBlur="validateText(familyName)">
<p id="familyNameText">Test 123</p>
Can anyone help me here?
Upvotes: 0
Views: 112
Reputation: 19772
As Kevmo mentioned a library, here is a quick and dirty example using jquery. Once you have the basics of javascript mastered look into jQuery, it will make your life a lot easier.
HTML not the absence on any calls to javascript functions and our required fields have the required
class
<form id="formToValidate">
<label for="familyName">Family name</label>
<input type="text" id="familyName" id="familyName" class="required">
<p class="requiredText">Family Name Required</p>
<label for="familyName">First name</label>
<input type="text" id="firstName" id="firstName" class="required">
<p class="requiredText">First Name required</p>
<label for="familyName">Dogs' name</label>
<input type="text" id="dogName" id="dogName">
</form>
CSS Just some basics
.requiredText {
display:none;
color:#F00;
}
label {
display:inline-block;
width:20%;
}
.required {
border-color:#F33;
}
input {
width:60%;
border:solid 1px #CCC;
margin-top:5px;
}
Javascript I've used the following from jquery:
$(document).ready(function () { /* Execute when DOM is loaded */
/*Assign blur event handler to fields with required class */
/*I have used the id of the form (#formToValidate) to scope the selctor.
Not required but a good practice*/
$("#formToValidate .required").blur(function () {
if ($(this).val() === "") { /*Check the value of the item being blured"*/
$(this).next(".requiredText").slideDown('fast'); /* Slide down the nearest alert text sibling*/
} else {
$(this).next(".requiredText").slideUp('fast'); /* Slide up the nearest alert text sibling*/
}
});
});
See this working example: http://jsfiddle.net/9Mb29/
Upvotes: 1