I'm creating a web front for a database using HTML, CSS, JavaScript and PHP for my uni coursework. I've only got so far as HTML and JavaScript form validation before I've run into this weird problem.
In my HTML, I link the JavaScript as follows:
<script type="text/javascript" src="dbicw2.js"></script>
Correct file name, I've checked.
Next, I have a form which takes a user's search. It upon submitting runs my JavaScript function, and its action is a PHP file. The code is as follows:
<form action="dbicw2.php" onSubmit="return validate(this)">
<input type="text" name="title">
<input type="submit" value="submit">
</form>
Again, correct PHP filename and JS function name.
Now, my JavaScript function seems to always return True, regardless of what happens. Currently, my JS looks like:
function validate(form)
{
alert("Hi")
for (var field in form.elements) { //For elements in form
field+="" //Incase it is undefined
alert("This element: '" + field.value + "'")
if (field.value.trim() == "") { //If the string is empty
alert(field.name + " is empty.") //Alert message
return false //Failed validation
}
}
return true //Otherwise, successful validation
}
Not even the alert message at the top runs. The form just goes through and PHP is loaded, regardless of the JS. The script neither works in Edge.
This is baffling because my code is a near clone of my professor's example, which works.
What is causing the Javascript to not be run and the PHP action done?
Edit: my professor's example code, which works:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>(prof name)</title>
<LINK REL='stylesheet' TYPE='text/css' HREF='dbicw.css'>
<script type="text/javascript" src="dbicw.js"></script>
</head>
<body>
<h1>Search for a Movie by Title</h1>
<form action="search_movie_example.php" onSubmit="return validate(this)">
Movie title:<br>
<input type="text" name="title">
<br>
<br>
<input type="submit" value="Search">
</form>
</body>
</html>
JavaScript:
function validate(form)
{
var ok=1
var msg=""
for (var i = 0; i < form.length; i++) {
if (form.elements[i].value.trim() == "") {
msg += "'" + form.elements[i].name + "' is void. "
ok=0
}
}
if (ok == 0) {
alert(msg)
return false
}
else {
return true
}
}