I’m just getting started with JavaScript & jQuery and am figuring things out as I go, so apologies if this is a basic question. I have some simple code written to:
- Capture a value from a form
- Store it to a cookie
- Recall the value from the cookie and store it in a JS variable
- Print the JS variable
…but I can’t get it to work. I can see that the cookie is being set properly, but for some reason, I can’t retrieve it and write it to the variable. Here is my code, any help would be much appreciated!
<!-- CAPTURE A VALUE IN A SIMPLE FORM... -->
<input id="txt" type="text" value="foo" />
<input id="btn" type="button" value="1 - write cookie" />
<input id="btntwo" type="button" value="2 - set cookie to variable" />
<input id="btnthree" type="button" value="3 - print the cookie" />
<!-- WRITE THE VALUE TO THE COOKIE WHEN A USER CLICKS THE BTN... -->
<script type="text/javascript">
$(document).ready(function () {
$("#btn").on("click", function () {
$.cookie('myCookie', $("#txt").val(), { expires: 365 });
});
});
</script>
<!-- SET THE COOKIE VALUE TO A VARIABLE WHEN A USER CLICKS THE BTNTWO... -->
<script type="text/javascript">
$(document).ready(function() {
$("#btntwo").on("click", function () {
var cookVal = $.cookie('myCookie')
});
});
</script>
<!-- PRINT THE COOKIE VALUE ON THE SCREEN WHEN A USER CLICKS THE BTNTHREE... -->
<script type="text/javascript">
$(document).ready(function() {
$("#btnthree").on("click", function () {
document.write(cookVal);
});
});
</script>
Your
cookValvariable is local to the click-handler function, anything outside will not be able to access it.Also, do not use
document.writein event handlers. If the HTML is fully parsed (and the DOM ready), the document is closed. Calls todocument.writeafter that will clear it and rewrite it.Btw, you might join your separate scripts to a single one, that might make the code more readable.
Demo at jsfiddle.net