Validating Form Data and Displaying Graphics with JavaScript
I have not really used JavaScript before but I am trying to validate form elements as they are being filled out. I have an X and a Check mark that I am trying to display next to the field to show if it is valid or not. I know that this is partially right because I can use an alert but I am not sure how to alter the fields of the graphics.
The JavaScript:
function validate_field(field)
{
var value = document.newAccount.fname;
if (value==null||value=="")
{
document.fnameX.visibility = visible;
document.fnameOK.visibility = hidden;
//alert("FAIL");
return false;
}
else
{
开发者_JAVA百科 document.fnameX.visibility = hidden;
document.fnameOK.visibility = visible;
//alert("TRUE");
return true;
}
}
Some of the HTML:
<form action="XXXXX" method="post" name="newAccount">
<table width="78%" border="0" align="center">
<tr>
<td colspan="2"><strong>Personal Info:</strong> </td>
</tr>
<tr>
<td width="24%"><div align="right">First Name: </div></td>
<td width="76%">
<input type="text" onchange="return validate_field(this)" onfocus="return validate_field(this)" name="fname" tabindex="1" size="50"/>
<img name="fnameX" src="redx.jpg" style="visibility:hidden" alt="X" width="18" height="18" /><img name="fnameOK" src="checkmark.jpg" style="visibility:hidden" alt="Ok" width="18" height="18" /></td>
</tr>
<tr>
<td><div align="right">Last Name: </div></td>
<td><input type="text" name="lname" tabindex="2" size="50"/></td>
</tr>
</table>
</form>
Your probably better off using CSS classes for something like this.
.valid
{
padding-right:15px
/*or whatever the width of your graphic is*/
background:url('checkmark.jpg') center right no-repeat;
/*remember that the url is relative to the stylesheet*/
}
.invalid
{
padding-right:15px
background:url('redx.jpg') center right no-repeat;
}
Then your validate function becomes:
function validate_field(field)
{
var value = field.value;
if (value==null||value=="")
{
field.parentNode.className = 'invalid';
return false;
}
else
{
field.parentNode.className = 'valid';
return true;
}
}
EDIT:
Remember to keep accessibility in mind, and that unless you are using an alert or making notifications accessible using ARIA attributes users with assistive devices are going to have a tough time with your form.
EDIT:
Here is a working example from your code where I change the background color of the parent table cell of the form input.
EDIT:
And here is an example where I got rid of those not so nice layout tables and replaced them with a fieldset
, and modified the Javascript a little bit. If you aren't familiar with jsbin you can append /edit
to the url to see/modify the code, like so.
精彩评论