it is a code to submit several grades in one submission
this is the javascript code fore validation
function validateForm() {
var x='<?php echo ($grade);?>';
if (x>100) {
alert("Invalid Data Entry");
return false;
}
it is not accessing the variable grade in the third echo down
<form name="form1" method="post" action="insertgradeac.php"onsubmit="return validateForm()" method="post">
<?php
$con = mysql_connect($server, $username, $password);
mysql_select_db($database);
$query_fetch5 = "SELECT ass_class FROM assess WHERE ass_ID LIKE '$id'";
$result_fetch5 = mysql_query($query_fetch5);
$row5 = mysql_fetch_row($result_fetch5);
$row5_0 = $row5[0];
$query_fetch = "SELECT st_ID, st_name FROM student WHERE class_ID LIKE '$row5_0'";
$result_fetch = mysql_query($query_fetch);
while ($row = mysql_fetch_row($result_fetch)) {
echo "<tr>
";
echo "<td>$row[0]<input type=\"hidden\" name=\"stt_ID[]\" value=\"$row[0]\" /></td>
";
echo "<td>$row[1]<input type=\"hidden\" name=\"student[]\" value=\"$row[1]\" /></td>
";
echo "<td><input type=\"text\" name=\"grade[]\" /></td>
";
echo "</tr>
";
}
mysql_close($con);
?>
That JS function will run in the browser, but it is trying to access a PHP variable that won't be set until after the form is submitted to the web server.
Try this instead:
function validateForm()
{
var grades = document.getElementsByName("grade[]");
for (var i = 0; i < grades.length; i++) {
if (Number(grades[i].value) > 100) {
alert("Grades cannot be more than 100.");
return false;
}
}
return true;
}
I've used the getElementsByName()
method to get a list of all of the grades[]
elements, then I loop over them testing their values and displaying the alert if the value is no good.
You don't actually say how you call validateForm()
, but I assume you do so from the submit event of your form.
Note that you should also add some code to confirm that the entered value is actually a number, and you need to do the same validation in your server-side PHP code in case a user has JS turned off (or uses browser dev tools to bypass your validation).
In the first block I notice:
You are setting x as a string... and later comparing it as a number/int. Remove the apostrophes when setting x.
In the second block I notice you are usong $id in your query without first setting (and sanitizing) it.