JavaScript code not run when clicking submit button in WordPress admin page form

I have created an HTML form in the admin pages of a WordPress installation. When I press the submit button I want the inserted data to be validated using a JavaScript function so that alerts are displayed when the data is not correctly inserted. I have tried all the things I have come across, but I have not been able to make it work. It should be something small, but I am not able to see it at this point.

The only thing I do is to echo out an HTML form to be shown using PHP and include some JavaScript function to be run. What is wrong in the code below? The {$this->form} part is just a string variable containing the HTML form. This works as expected.

public function __toString()
{
    return "
        <script>
        function validateForm()
        {
            alert("FOOOOO");
            return false;
        }
        </script>
        <h1>Heading</h1><br>
        <form method="post" onsubmit="return validateForm()">
            {$this->form}<br>
            <input type="submit" name="submit" value="Submit me!" /><br>             
        </form>
    ";
}

Related posts

1 comment

  1. In this case, the error turned out to be naming the JavaScript function validateForm(), as this is an internal function in the WordPress core. Changing it to validate_form() or whatever fixes the issue.

Comments are closed.