PDA

View Full Version : JavaScript Form Validation


AndrewAK
04-11-2004, 11:03 AM
I've got this form. So far, I can loop through it and check each element to see if it's blank. I want to set the focus to the last element. Example: Message "txtOne is Blank". After clicking OK I want the focus to return to, in this case, to txtOne. In short, I want to set the focus to the object that is indicated in the last message/alert.

Here is the code.

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
function setFocus_onload()
{
document.form1.txtOne.focus();
}

function checkBlank_onclick()
{
var i;
var myform = document.form1;

for (i = 0; i <= 4; i++)
{
if(myform.elements[i].value == "")
{
alert(myform.elements[i].name + " is blank.")
}
}
}

</script>

</head>

<body>
<form action="confirm.asp" method="post" name="form1">
Item1<input name="txtOne" type="text" /><br />
Item2<input name="txtTwo" type="text" /><br />
Item3<input name="txtThree" type="text" /><br />
Item4<input name="txtFour" type="text" /><br />

<input name="submit" type="button" value="Sumbit" onclick="checkBlank_onclick()"/><br />
<input name="reset" type="button" value="Reset" />
</form>
</body>
</html>

wiffles
04-11-2004, 11:31 AM
Ahem:

alert(myform.elements[i].name + " is blank.")
myform.elements[i].focus()

This should work.

AndrewAK
04-11-2004, 11:55 PM
I've run into a problem with this. When I use onblur() to fire the function, the focus is given to the next element. The code then falls into an infinit loop. I need to be able to break out of the loop, set the focus to the previous element, then begin again from where the loop left off.

wiffles
04-12-2004, 10:16 AM
I tried it and it didn't get stuck in a loop - but it did nag about more than one blank. So after my line put this:

break

Then, going through the loop one more time can't hurt. :)