Friday, October 31, 2008

Validating Form Entries with JavaScript PS

OK. Being new to Blogger, I didn't realize how to correctly post code samples to an entry. Hence the screen captures in my last post. Below is a copy-and-paste-friendly version of the whole page of code I used for that example.

<html>
<head>

<script type="text/JavaScript">
<!--
function check_form_data()
{
if (document.the_form.email.value == "")
{
alert("Email is a required field. Please fill it in.");
document.the_form.email.focus();
document.the_form.email.style.background = "#EEF111";
return;
}else{
document.the_form.submit();
}
}
// -->
</script>

</head>

<body>

<?php
if (isset($_POST['test_val'])){
process_form();
}else{
print_form();
}

function print_form(){
print <<< FORM_TEXT
<!--Note that the action just points back to the same page-->
<form name="the_form" method="POST" action="this_page.php">
<!--Here is our test value-->
<input type="hidden" value="1" name="test_val">
Email: <input type="text" id="email" size="20"><br>
<input type="button" onClick="check_form_data();" value="Submit">
</form>
FORM_TEXT;
}

function process_form(){
//Process the form data - send an email, write to a DB, whatever.
}
?>

</body>
</html>

No comments: