I want to change HTML document elements when the onsubmit event handler returns false.
Inside function validate()
a cookie is set (BTW, is there simpler way than cookie?).
Onload event handler checkIfFalseSubmit()
checks cookie and runs function changeDocument()
that changes document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>How change document after false onsubmit without manual page reloading</title>
<script type="text/javascript">
function validate() {
// http://www.javascripter.net/faq/settinga.htm
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 1000*5000);
document.cookie = "cookie1=a; expires=" + expire.toGMTString();
alert ("Always false - just for testing");
return false;
}
function changeDocument() {
myDiv.innerHTML = "Form validation failed";
}
// http://stackoverflow.com/questions/10730362/javascript-get-cookie-by-name
function getCookie(name) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function checkIfFalseSubmit() {
if ( getCookie("cookie1") == "a")
changeDocument();
}
</script>
</head>
<body onload="checkIfFalseSubmit()">
<div id="myDiv">Before Submit</div>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" name="f" onsubmit="return validate();" >
<input type="text" name="myName" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Problem is that onload
happens only when I manually reload page.
Without reloading the alert is shown but the document remains unchanged.
Is there another event that I should use instead of onload for my purpose? Is there another way to get my goal?