Javascript cookie not working on form submit
-
22-09-2019 - |
Question
I have a form like this:
<form id="loginCompact" action="https://externalsite..." name="sportsbook" method="post" onsubmit="createCookie('BRLOG', document.sportsbook.username.value, 1)">
<input type="text" name="username" class="loginUsername" />
...other fields...
</form>
And this is the Javascript function that's called:
<script type="text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/; domain='mydomain.com'";
}
</script>
However, the cookie is not getting set when the form is submitted. It was working fine when attached to the onclick
handler of the button, but not on onsubmit
. Any ideas?
Solution 2
I figured this out - I needed to put a full stop in front of the domain, and lose the quotes:
domain=.mydomain.com
OTHER TIPS
Check to make sure onsubmit is spelled correctly (maybe it's onSubmit?).
Simplify by putting an alert in instead of a call to your function
onsubmit="alert('test')"
Put an alert at the top of your function to see if it's getting called and the cookie isn't being set for some more complicated reason.
If it is getting called, check to make sure that all of the variables your rely on are correct, using alerts, or (better), something like firebug.