PDA

View Full Version : Resolved Javascript Form Validation



keyboard
09-20-2011, 09:51 AM
If the field is empty it should make an alert message saying you need to fill in your first name. Else it should submit the form. The alert message works but even if you do put something into the text input the form won't submit?

Any help would be great.


<?php
require "database.php";
if (isset($_POST['submit']))

{
echo "hello";
}
else

{
?>

<html>
<head>
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}

}

</script>
</head>

<body>
<form name="myForm" action="<?php echo $_SERVER['PHP_SELF']?>" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>

</html>

<?php
}
?>

Minos
09-20-2011, 03:19 PM
Try adding:



alert("First name must be filled out");
return false;
}
return true;
}

keyboard
09-21-2011, 11:14 PM
I changed what you suggested but it still won't work. However, if I change the target of the form to an external php processing page it works fine? Any help?

jscheuer1
09-22-2011, 12:53 AM
Your script should and does work as originally written. If the fname field is null or empty, you get the alert and the submission returns false so doesn't occur. If there's something in the fname field, there's no alert and the function returns undefined, so the submission goes through. You can observe this because the page reloads, evidenced by the fact that the fname field empties. After all $_SERVER['PHP_SELF'] is the action, so that's what one would expect.

Ah, but you might say - I was expecting a successful submission to show a page with only:


hello

on it, because in the PHP it has:



if (isset($_POST['submit']))

{
echo "hello";
}
else

{

Well, $_POST['submit'] will never be set because there is no input in the form with the name 'submit'. If you add it to the submit button:


<form name="myForm" action="<?php echo $_SERVER['PHP_SELF']?>" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input name="submit" type="submit" value="Submit">
</form>

Then things will perform as I imagine is expected.