2

I already have a php validation and form setup with PHP. So if someone forgets a username, the validation will add to the errors array and display it on the page when submitted. Now, instead of displaying some text for the error (Username can't be blank) I just want the input box highlighted in red, which I know needs JavaScript. I am having some trouble running this JavaScript function properly. Below is the code.

JavaScript:

<script type="text/javascript">
function myFunction() {
document.getElementById("usernameformitem").className = "formerror";
}
</script>

PHP:

if (isset($_POST['submit'])) {

$required_fields = array("username");

function validate_presences($required_fields) {
global $errors;

foreach($required_fields as $field) {
    //the $value is now the un/pw without whitespaces 
    $value = trim($_POST[$field]);
    //if the value does not exist/is blank
    if (!has_presence($value)) {
        //remember field is really un or pw
        $errors[$field] = fieldname_as_text($field) . " can't be blank";
        echo "<script>";
        echo "myFunction();";
        echo "</script>";
    }
  }
}


validate_presences($required_fields);

HTML:

<form action="new_user4.php" method="post">
<div id="usernameformitem">
  <p>Username:
    <input type="text" name="username" value="" />
 </p>
 </div>

  <input type="submit" name="submit" value="Create User" />
</form>

Thanks in advance!

Drake491
  • 67
  • 1
  • 12
  • Maybe HTML5 input validation is an option for you (to avoid JS)? E.g.see: http://stackoverflow.com/questions/10281962/is-there-a-minlength-validation-attribute-in-html5 – RhinoDevel Jul 05 '15 at 16:01

2 Answers2

0

make sure the div exists before calling the function, for example echo the script after the div or use

window.onload=function() { if (myFunction) myFunction(); }

FIDDLE

But why even submit the form?

window.onload=function() { 
  document.getElementById("form1").onsubmit=function() {
    if (this.username.value="") {
      myFunction();
      return false; // stop submission
    }
    return true;
  }
  <?PHP if (!has_presence($value)) { ....  ?>
  if (myFunction) myFunction();
  <?PHP } ?>
}

PS: NEVER call a form element name="submit" - it will block you from ever submitting by script

mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

Right under the if submit area of php, I echoed

echo "<script type=\"text/javascript\">";
echo "function myFunction() {";
echo "document.getElementById(\"usernameformitem\").className =    \"formerror2\";";
echo "}";
echo "</script>";  

Then, in the HTML under the div that I am trying to affect, I entered:

<script>
    window.onload=function() { if (myFunction) myFunction(); }
 </script>

Only problem I ran into was that style had to be internally set. I'm not sure how to have it pull from my external css yet.

Big thanks to mplungjan!

Drake491
  • 67
  • 1
  • 12