1

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?

mwloda
  • 491
  • 1
  • 6
  • 13

1 Answers1

0

I think it is overly convoluted. You don't have to use cookies and and body onload event. Just keep validate() called on form submit and changeDocument() to display your message.

Inside of validate() if validation failed call changeDocument() before returning false.

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
  • **It works**. Your response answers _exactly_ the question I stated. No complains. But for more complicated example (more events, more document changes), what's the best way to remember page state client-side? – mwloda Sep 19 '13 at 07:19
  • You don't need to remember client state for validation - if validation fail, form simple won't be submitted. If you need this for a different scenario - please specify which one. – Yuriy Galanter Sep 19 '13 at 12:02
  • Thanks for your reply. Now, I have no different scenario. I see, my true problem is understanding browser behavior when onsubmit handler returns its value. I've been expecting some _special_ event. – mwloda Sep 19 '13 at 18:02