简体   繁体   English

JavaScript 无法从 HTML 表单正确运行

[英]JavaScript not running correctly from HTML form

I'm creating a web front for a database using HTML, CSS, JavaScript and PHP for my uni coursework. 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.在遇到这个奇怪的问题之前,我只进行了 HTML 和 JavaScript 表单验证。

In my HTML, I link the JavaScript as follows:在我的 HTML 中,我将 JavaScript 链接如下:

<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.它在提交时运行我的 JavaScript function,它的作用是 PHP 文件。 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.同样,更正 PHP 文件名和 JS function 名称。

Now, my JavaScript function seems to always return True, regardless of what happens.现在,无论发生什么,我的 JavaScript function 似乎总是返回 True。 Currently, my JS looks like:目前,我的 JS 看起来像:

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.表单刚刚通过并加载了 PHP,无论 JS 是什么。 The script neither works in Edge.该脚本在 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?是什么导致 Javascript 无法运行并且 PHP 操作完成?

Edit: my professor's example code, which works:编辑:我教授的示例代码,它有效:

HTML: HTML:

<!DOCTYPE html>
<html>
    <head>
            <title>Milena Radenkovic</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: 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
        }
    
}

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.您使用for (var field in form.elements)迭代表单元素,但这将迭代表单元素的索引值,而不是实际元素。 Change in to of to iterate over the actual values instead.更改in of以迭代实际值。

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
}

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.我添加了一个event.preventDefault()以便页面不会在实时示例中被重定向,并更改了in to of同时还更改了“获取”输入元素的语句。 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 . of只是允许您遍历数组,而实际的选择器只是获取所有非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.我再次将in更改为of ,并添加了一个扩展运算符以将 HTMLFormControlsCollection 转换为数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM