I'm running a PHP code to validate login form and if there's an input empty it should run a javscript function that changes the display attribute of some DIVs to block. If I put my JS code between the head tag it says
Uncaught TypeError: Cannot read property 'style' of null
, and If I put my code before the /body tag it says
Uncaught ReferenceError: formValidation is not defined
Javascript code:
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 code:
else {
echo "<script> formValidation(); </script>";
}
At the time you execute formValidation()
the DOM elements are not ready.
You need to catch the page load event and then execute the style change.
document.addEventListener("load", formValidation);
Try to use
window.onload=formValidation;
It is executed when web page has completely loaded all content.
You Can use JQuery for checking document ready event.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
Use this HTML code in your document
else{
echo '<script type="text/javascript">
$( document ).ready(function() {
formValidation();
});
</script>';
}
Edit your php code and try this
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.