-2

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>";
    }
Sergiu Turus
  • 27
  • 1
  • 1
  • 8
  • 1
    it is better to validate form in function using if else statements, and then alert the user about the empty and then focus to that field and add css instead doing this in php with JavaScript. if php and JavaScript are separate then it is also easy to handle the errors. – Hamza Zafeer Apr 21 '16 at 14:18
  • If you're running the validation through PHP, why aren't you setting those styles directly by PHP...? I'm very much suspecting a duplicate of http://stackoverflow.com/a/13840431/476 here... – deceze Apr 21 '16 at 14:44

3 Answers3

1

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);
Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
0

Try to use

window.onload=formValidation; 

It is executed when web page has completely loaded all content.

No Sound
  • 113
  • 1
  • 11
0

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

cemsina güzel
  • 390
  • 4
  • 14