2016-04-21 39 views
-2

我正在运行PHP代码来验证登录表单,如果输入为空,它应该运行一个javscript函数,该函数将某些DIV的显示属性更改为阻止。 如果我把脑袋标签之间我的JS代码,它说试图在PHP代码中调用js函数

Uncaught TypeError: Cannot read property 'style' of null

,如果我把我的代码/标记之前它说

Uncaught ReferenceError: formValidation is not defined

Javascript代码:

function formValidation() { 
    document.getElementById("errMessage").style.display = "block", 
    document.getElementById("arrow-errMessage").style.display = "block", 
    document.getElementById("errEmail").style.display = "block", 
    document.getElementById("arrow-errEmail").style.display = "block"; 
} 

PHP代码:

else { 
      echo "<script> formValidation(); </script>"; 
    } 
+1

最好是使用if else语句来验证形式的功能,然后提醒用户有关空白,然后专注于该字段并添加css,而不是使用JavaScript在php中执行此操作。如果php和JavaScript是分开的,那么它也很容易处理错误。 –

+0

如果您通过PHP运行验证,为什么不直接通过PHP设置这些样式...?我非常怀疑这里http://stackoverflow.com/a/13840431/476的重复... – deceze

回答

1

当您执行formValidation()时,DOM元素尚未准备好。
您需要捕捉页面加载事件,然后执行样式更改。

document.addEventListener("load", formValidation); 
0

尝试使用

window.onload=formValidation; 

在网页完全加载的所有内容时执行。

0

您可以使用JQuery来检查文档就绪事件。

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js"></script>

使用您的文档

else{ 
echo '<script type="text/javascript"> 
    $(document).ready(function() { 
     formValidation(); 
    }); 
</script>'; 
} 

编辑你的PHP代码在此HTML代码,并尝试这种