[英]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.提交后,我有一个 PHP 脚本,用于检查输入框是否为空。 If it is, it displays an error message and runs a Javascript function.如果是,它会显示错误消息并运行 Javascript 函数。
My problem is that the error message appears, but the Javascript function doesn't execute.我的问题是出现了错误消息,但 Javascript 函数没有执行。
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 ?你的 JavaScript 函数实际上在哪里执行? 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.