Run a JavaScript function based off of PHP validation and form submit -
i have php validation , form setup php. if forgets username, validation add errors array , display on page when submitted. now, instead of displaying text error (username can't blank) want input box highlighted in red, know needs javascript. having trouble running javascript function properly. below 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 $field) { //the $value un/pw without whitespaces $value = trim($_post[$field]); //if value not exist/is blank if (!has_presence($value)) { //remember field un or pw $errors[$field] = fieldname_as_text($field) . " can't 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!
make sure div exists before calling function, example echo script after div or use
window.onload=function() { if (myfunction) myfunction(); }
but why submit 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 form element name="submit"
- block ever submitting script
Comments
Post a Comment