简体   繁体   中英

Javascript form validation doesn't execute

I have an input box. Upon submit, I have a PHP script which checks to see if the input box is empty. If it is, it displays an error message and runs a Javascript function.

My problem is that the error message appears, but the Javascript function doesn't execute.

Here's my script:

<?php    
if(isset($_POST['submit'])) {

    $username = $_POST['username'];

    if(empty($username)) {
        echo 'Please enter a username';

        echo"
            <script>
            window.onload = function () {
                function validate(e) {
                    var username = document.getElementById('username');
                    if (username.value.trim() == '') {
                        username.classList.add('error');

                        setTimeout(function() {
                            username.classList.remove('error');
                        }, 300);
                        e.preventDefault();
                    }
                }
            }
            </script>
            ";

    }else{
        // something here
    }
}
?>

<form method="post" id="login">
    <input type="text" id="username" name="username">
    <input type="submit" name="submit">
</form>

Where does your JavaScript function actually get executed ? Removing the logic, the structure of what you have is:

window.onload = function () {
  function validate(e) {
    //...
  }
}

So when the window loads, you execute a function. That function does nothing more than define another function. Nothing ever executes that other function.

If you want to execute that code when the window loads, don't wrap it in a function. Just execute it:

window.onload = function () {
  // validation logic here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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