Reputation: 213
im working on a project about a web-based system. I have a form, i want to check if all the fields are filled in but when one of the fields is empty it will show a prompt and will not record the data to the database unless the form have been completed. I am able to show a prompt if the fields is empty but still, it records the data provided even if one or some of the filled is empty.
Here is my html form code:
<script type='text/javascript'>
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus();
return false;
}
return true;
}
<form action="insert.php" method="post">
FNAME: <input type="text" name="fname" maxlength="50" id="required"/>
MNAME: <input type="text" name="mname" maxlength="50" id="required"/>
LNAME: <input type="text" name="lname" maxlength="50" id="required"/><br/>
Male <input type="radio" name="gender" value="male" /><br/>
Female <input type="radio" name="gender" value="female" /><br/>
College:
<select name="college">
<option value="default"> --- </option>
<option value="CEC">CEC</option>
<option value="CAD">CAD</option>
<option value="COB">COB</option>
</select>
</br>
<input type="submit" name="formSubmit" onclick="notEmpty(document.getElementById('required'), 'Please Enter a Value')"
value='SUBMIT'/>
</form>
my php code:
<?php
$con = mysql_connect("localhost","abs","abs");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$sql="INSERT INTO name (fname, mname, lname, gender, college)
VALUES
('$_POST[fname]','$_POST[mname]','$_POST[lname]','$_POST[gender]','$_POST[college]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
I can't get it to work. I am new at php. please help me. Thanks a lot !!
Upvotes: 1
Views: 6904
Reputation:
Something wrong in your code. You are passing one element's id and want to check all elements. Also Id of all fields is same.
Suggesting you a link : http://www.javascriptkit.com/script/script2/formrequired.shtml
showing a live example what you want. You can take code from here and try.
Upvotes: 2
Reputation: 78770
Your function is returning a value but you are not using it.
onclick="return notEmpty(...
A false return value will stop the submit.
This is the reason the form still gets submitted to the backend.
In addition, id
should always be unique. Using getElementById
will only return you a single element so you are not actually checking all of your required fields. You could instead assign a class of required and loop over the elements.
Upvotes: 1