简体   繁体   中英

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 alert s 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>
    ";
}

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.

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