2

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
        }
    
}
5
  • 1
    Do you see any error in the console (press F12 in Edge, Console tab)? Do you see any non 200 status codes in Network tab when you refresh the page? Commented Mar 24, 2021 at 14:43
  • Nope, no errors in F12, cache is disabled, etc.... And it just fixed itself. I didn't make any change to my JS but now my test alert() shows. Baffling Commented Mar 24, 2021 at 14:48
  • "This is baffling because my code is a near clone of my professor's example, which works." How do they differ? Commented Mar 24, 2021 at 14:55
  • @HoldOffHunger I have edited my question to include it. I used my professors code as boiler plate, the main differences are the JS files referenced, and the method of verifying an empty form. A test alert() at the top will run. Commented Mar 24, 2021 at 15:02
  • 1
    I lost 6 rep for this question 😂. Stack overflow is a joke Commented Jul 27, 2021 at 13:54

2 Answers 2

3

I think I found a mistake (hopefully THE mistake) in your code. It's really simple, but very common.

You iterate over your form elements using for (var field in form.elements), but this will iterate over the index values of the form elements, rather than over the actual elements. Change in to of to iterate over the actual values instead.

Example:

let arr = ['foo', 'bar', 'cat'];

for (let word in arr) {
  console.log(word);    // prints 0, 1, 2
}

for (let word of arr) {
  console.log(word);    // prints foo, bar, cat
}
Sign up to request clarification or add additional context in comments.

2 Comments

To add to this: Your professor's code also iterates over the index, but then they use form.elements[i] to access the element. Changing your loop into for (var field of form.elements) should work.
Thanks for this, made this change and the issues have sorted themselves out.
0

Try this:

function validate(form) {
  event.preventDefault();
  alert("Hi")
  for (var field of [...form.querySelectorAll('input:not([type="submit"])')]) { //For elements in form
    alert("This element: '" + field.value + "'")
    if (field.value.trim() == "") { //If the string is empty
      alert(field.name + " is empty.") //Alert message
    }
  }
}
<form action="dbicw2.php" onsubmit="validate(this)">
  <input type="text" name="title">
  <input type="submit" value="submit">
</form>

I added an event.preventDefault() so the page wouldn't be redirected in the live example, and changed the in to of while also altering the statement that "fetches" the input elements. The of simply allows you to iterate through the array, and the actual selector just gets all the input elements that are not of the type submit.

If you only want to alter your code to make it work, then try this:

function validate(form) {
  alert("Hi")
  for (var field of [...form.elements]) { //For elements in form
    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
}
<form action="dbicw2.php" onSubmit="return validate(this)">
  <input type="text" name="title">
  <input type="submit" value="submit">
</form>

I again changed the in to of, and added a spread operator to convert the HTMLFormControlsCollection to an array.

3 Comments

Could you explain why a form element value may be undefined, even after entering something in the field? On an alert() printing field.value it says undefined, using console.log(), it says the true value
Sorry, I'm not exactly sure what you're asking. Could you rephrase that, please?
Don't worry, the problem was that my variable from iterating through form.elements was appearing to have different values when I printed it in different ways. Solved it now. 👍

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.