How can I save variables on refresh? - javascript

<!DOCTYPE HTML>
<html>
<head>
<title>Zautra Levels</title>
<h2 style="font-family: Trebuchet MS; color: blue;"">Zautra Levels</h2>
<p> </p>
</head>
<body>
<p>Clickables:</p>
<button id="swag" onclick="lmao()">Gain XP</button> <button id="gold" onclick="getgold()">Get Gold</button> <button id="buyupgrade" onclick="buyupp()">Level Up!</button>
<p> </p>
<div id="total">XP: 0</div>
<div id="goldt">Gold: 0</div>
<div id="upgradess">Level: 0</div>
<div id="upcostt">Required XP: 25</div>
<script>
var clicks = 0; // How many clicks you have
var upgrades = 0; // How many upgrades you have purchased
var upcost = 25; // How much the upgrades cost
var gold = 0; // How much gold you have
function updateclicks() { // Declares the function that updates the "Zautra Clicks" Text.
var v=document.getElementById("total");
v.innerHTML = 'XP: ' + clicks;
}
function updategold() { // Declares the function that updates the "Zautra Clicks" Text.
var g=document.getElementById("goldt");
g.innerHTML = 'Gold: ' + gold;
}
function updateupgradecounter() { // Declares the function that updates the "Upgrades:" Text.
var y=document.getElementById("upgradess");
y.innerHTML = 'Level: ' + upgrades;
}
function updateupcost() { // Declares the function that updates the "Upgrade Cost:" Text.
var z=document.getElementById("upcostt");
z.innerHTML = 'Required XP:' + upcost;
}
var x=document.getElementById("swag"); function lmao() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
clicks+=1;
updateclicks();
}
var j=document.getElementById("gold"); function getgold() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
gold+=1;
updategold();
}
var c=document.getElementById("buyupgrade"); function buyupp() {
if (clicks >= upcost) {
clicks-=upcost
upgrades+=1
upcost*=2
updateclicks();
updateupgradecounter();
updateupcost();
}
else
{
var clicksdif = upcost - clicks;
confirm("You need " + clicksdif + " more XP to level up.");
}
}
</script>
</body>
</html>
This is the code for my game that I am working on.
I'm trying to add a button, and when you press it, it saves all of the variables.
If you're level 5 with 26 XP, and 7 gold, you refresh the page, you still have those stats instead of losing them on refresh.
Please help!
(And yeah, I do realize that the code is really messed up, but that is a small issue. I'll fix that sooner or later.)

I believe that actually the easiest way, easier than cookies, is to pass the values via the URL. Example:
<form action="yourPage.php?gold=$amount&level=$whatlevel&experience=$experience" method="POST">
//Your refresh button here
</form>
and then to retrieve those variables when the page reloads, use: gold=$_POST['gold']
Another option as well is to use the GET method instead of POST.
Keep in mind that the file extension needs to be php for this code to work.

you could create a cookie in php:
setcookie("NameOfTheCookie",$value,$expireTime)
and $value can be an array of values as well.

Related

How to create 'add to favourite' feature in a html cordova android app?

I am creating a song book app using phonegap. In index.html i have list of songs in li tags. when i click on a particular song it will open that particular song's lyrics in another local html file.
I want to add a 'favourite button'. When the favourite button is clicked I want that particular song to be added to the favourites list. When user open the favourite page it should display list of their favourite songs, and when they click a song in favourite page it should open that particular song's lyrics html page.
I am an intermediate user of HTML and a beginner in JavaScript.
Please help me accomplish this,
Thanks in advance.
Because this is a 'pretty broad' question, it is hard to find an answer for this, but I'd suggest making an array, storing the favorite songs into it, then when you open the favorites.html page, it gets the array, and writes the information to the page.
e.g. when a favorite button is clicked on a song page, it writes: the name of the song(exampleSong), the page of the song(exampleSong.html), and other random details that you need, and going to the favorites.html should get a document ready function that reads the array and writes the page.
Sorry if I can't help that much, but this was a really broad question.
If you need help, here are some examples that I created
(This gets the array of favorites, and prints them out)
var favorites = [
["ExampleSong", "exampleSong.html"],
["LorddirtCoolSong", "LorddirtCoolSong.html"],
["StackOverflowIsAwesome", "StackOverflowIsAwesome.html"]
];
var containerA = document.getElementById("favoritesA");
for (var i in favorites)
{
for (var j in favorites[i])
{
var newElement = document.createElement("p");
newElement.innerHTML = favorites[i][j];
containerA.appendChild(newElement);
}
}
var containerB = document.getElementById("favoritesB");
for (var i in favorites)
{
var newElement = document.createElement("p");
newElement.innerHTML = "<h4>Favorite Song " + i + "</h4>";
containerB.appendChild(newElement);
for (var j in favorites[i])
{
var newElement = document.createElement("p");
newElement.innerHTML = favorites[i][j];
containerB.appendChild(newElement);
}
}
var containerC = document.getElementById("favoritesC");
for (var i in favorites)
{
var newElement = document.createElement("p");
newElement.innerHTML = "<h4>Favorite Song " + i + "</h4>";
containerC.appendChild(newElement);
for (var j in favorites[i])
{
if(j == 1){
}else{
var newElement = document.createElement("p");
newElement.innerHTML = "<a href='" + favorites[i][1] + "'>" + favorites[i][j] + "</a>";
containerC.appendChild(newElement);
}
}
}
.favoriteSongs{
border: 2px solid black;
display: block;
}
<!--
EXAMPLE 1A: Print out the Favorites
-->
<hr>
<h2>Example 1A: Print favorites out</h2>
<div id='favoritesA' class='favorites'>
</div>
<hr>
<!--
EXAMPLE 1B: Now you know the order of the songs!
-->
<h2>Example 1B: Print favorites out with formatting</h2>
<div id='favoritesB' class='favorites'>
</div>
<hr>
<!--
EXAMPLE 1C: Link them
-->
<h2>Example 1C: Link to the page</h2>
<div id='favoritesC' class='favorites'>
</div>
<hr>
Very self explanatory, it gets the array of favorite songs, with the name and url, gets the container, which is <div id='favorites'></div> and writes the contents into it.
(oh wait, i just noticed I spent so long working on this hahaha.)
Examples:
1A: All I did was search the array favorites, and print out every single thing in the array. Simple.
1B: Slightly different, it's the same as the last, but I added a <h4> tag before every array in the array. (Yes, arrays inside arrays inside arrays are confusing).
1C: Instead of printing out both of the arrays inside the arrays, just print out the first thing inside the arrays in the arrays, and add a link pointing to the second thing inside the arrays in the arrays. Confused already? Just read it through and you'll understand.
Hi I found a solution using another SO question.
First we will create a local storage and store song details in that local storage key.
then we will retrieve that information in favorite.html using localStorage.getItem(key);
The following is my code for first song song1.html
when button pressed song link will be appended to local storage
<!DOCTYPE html>
<html>
<body onload="mySong()">
<button onclick="mySongOne()">add to favorite</button>
<script>
function mySong() {
localStorage.setItem("favsong", "");
}
function appendToStorage(name, data){
var old = localStorage.getItem(name);
if(old === null) old = "";
localStorage.setItem(name, old + data);
}
function mySongOne() {
appendToStorage("favsong", "<a href='https://www.song1.com'><h1>song1</h1></a>");
}
</script>
</body>
</html>
for another song song2.html
when button pressed second song link will be appended to local storage
<!DOCTYPE html>
<html>
<body>
<button onclick="mySongTwo()">add to favorite</button>
<script>
function appendToStorage(name, data){
var old = localStorage.getItem(name);
if(old === null) old = "";
localStorage.setItem(name, old + data);
}
function mySongTwo() {
appendToStorage("favsong", "<a href='https://song2.com'><h1>song2</h1></a>");
}
</script>
</body>
</html>
and favorite.html
on page load it will show details from local storage
<!DOCTYPE html>
<html>
<body onload="yourFunction()">
<div id="result"></div>
<script>
function yourFunction() {
document.getElementById("result").innerHTML = localStorage.getItem("favsong");
}
</script>
</body>
</html>

JavaScript returning null on a function for a simple guessing game

I created a guessing game using JavaScript. Initially, I wrote it in codepen where it ran fine, and when I moved it over to sublime to test it in the browsers as a standalone, the code did not work. I am getting this error: "Uncaught TypeError: Cannot read property 'value' of null at guess" which is line 14 var guessValue = parseInt(guessIn.value); and links back to the HTML of line 20 which is Guess
I can't figure out where the null is coming from. What am I doing wrong or haven't defined properly that is causing the null? I removed the CSS to blank slate it and make sure that wasn't screwing anything up.
//Generate random number between 1 and 500
var randomNumber = Math.floor((Math.random() * 500) + 1);
//Create variables to store info for loops and displaying info back to user
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
var counter = 0;
//function runs when the guess button is hit
function guess() {
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
//if statement for finding the value and reporting to the user
//check if the counter is less than 10 and guessValue is not empty
if (counter < 10 && guessValue) {
counter++;
}
//the guess is correct
if (guessValue == randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' You have correctly guessed the number. You may escape.';
}
// the guess is greater
if (guessValue > randomNumber) {
guessOut.value = guessOut.value + '\n' +"Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is lower.';
}
//the guess is lower
if (guessValue < randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is higher.';
}
//when all 10 guesses are used
else if (counter == 10) {
guessOut.value = guessOut.value + '\n' + "You did not guess the number I was thinking, " + randomNumber + "." + " You have met your end. Goodbye.";
}
return false;
}
//Show the number to guess upon clicking the checkbox for Cheat
function cheat() {
if (document.getElementById('cheat').checked) { document.getElementById('cheatNumber').value = randomNumber;
document.getElementById('cheatShow').style.display = 'inline';
}
else { document.getElementById('cheatNumber').value = '';
document.getElementById('cheatShow').style.display = 'none';
}
}
//function to reset the game
function reset() {
//reset guess value
userGuess.value = "";
//reset text area
guessesMade.value = "";
//reset counter
counter = 0;
//set new random number for play
randomNumber = Math.floor((Math.random() * 500) + 1);
return false;
}
<html>
<head>
<title>Do You Wanna Play A Game?</title>
<script src="game.js"></script>
</head>
<body>
<h1>Do You Wanna Play A Game?</h1>
<h3>A Guessing Game</h3>
<fieldset>
<legend>The Game Starts Now</legend>
<p>Welcome. You have stumbled upon this page. As a consequence, you have been trapped. To get out, the objective is simple.</p>
<p>I am thinking of a number. This number is between 1 and 500. You get ten guesses.</p>
<p>Good luck.</p>
<div id="guessingarea">
<input type="text" id="userGuess" value="394" /><br />
<button onClick="guess();">Guess</button>
<button onClick="reset();">Reset</button>
<br />
<input id="cheat" type="checkbox" value="cheat" onClick="cheat();" />
<label for="cheat">Cheat</label>
<div id="cheatShow" style="display: none;">
<input id="cheatNumber" type="text"/>
</div>
</div>
</fieldset>
<p></p>
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
</body>
</html>
It looks like you are including the script before your html document.
document.getElementById('userGuess');
is called before the element 'userGuess' exists.
I can think of two solutions to this, either include the script at the end of the document, or access this element only when you need it, rather than declaring it at the beginning like so:
var guessValue = parseInt(document.getElementById('userGuess').value);
You have included the script, before the element is available. As soon as the parser, hits the JS file, it will stop the rendering of the page and try to parse javascript. When the script is encountered, the element is still not available.
You have 2 options to make this work.
Move the script tag to before the close of the body element. This will make sure the page has the available elements before manipulating them.
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
<script src="game.js"></script>
</body>
Query the elements every single time inside the guess method since it is only invoked on a click action, which happens only after page is rendered.
function guess() {
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
......
......
The reason it works on code pen is because, the scripts are executed are deferred to onLoad which makes sure the elements are available on the page.
If you move the variable declarations inside the function it will work. The issue is that the JavaScript code is executed before the document is ready so the guessIn and guessOut variables are initialised to null.
Alternatively you can wrap your JavaScript code in a function that will execute when the DOM is complete.
document.onreadystatechange = function () {
if (document.readyState === "complete") {
// your code goes in here
}
}
See MDN for more details.

Change innerHTML based on date comparison

I currently have the following code showing:
<h1 id="header1" class="loginhead">Welcome to the <%=formFields.getDisplayValue("programName")%> Registration Site, .</h1>
I need to replace it with:
<h1 id="header2" class="loginhead" >The <%=formFields.getDisplayValue("programName")%> Registration Site, is now closed.</h1>
I need the replace to happen when the date and time are 7/15/15 11:59PM PT
Any way to do this using Jquery, JSP or Javascript?
Update**
<h1 id="header" class="loginhead" ><span id='welcome'></span><span id='welcome2'></span> <%=formFields.getDisplayValue("programName")%> Registration Site <span id='closed'></span> </h1>
<script>
var now = new Date().getTime(); //Return the number of milliseconds since 1970/01/01:
var epochTimeJul15_1159pm = 1437019199000; // number of milliseconds since 1970/01/01 at Jul 15_11:59:59pm. See http://www.epochconverter.com/.
var timeTillChange = epochTimeJul15_1159pm - now;
function changeHeader(){
document.getElementById('closed').innerHTML = ' is now closed.'; //change the html/text inside of the span with the id closed'.
}
function changeHeader1()
{
if(epochTimeJul15_1159pm <= now)
{
document.getElementById('welcome').innerHTML = 'The ';
}
}
function changeHeader2()
{
if(now < epochTimeJul15_1159pm)
{
document.getElementById('welcome2').innerHTML = 'Welcome to the ';
}
}
setTimeout(changeHeader, timeTillChange); //will wait to call changeHeader function until timeTillChange milliseconds have occured.
setTimeout(changeHeader1, timeTillChange);
setTimeout(changeHeader2, timeTillChange);
</script>
First make it easier to use javascript to edit your html. We will do this by creating an empty span to insert the closed message into:
<h1 id="header" class="loginhead" >Welcome to the <%=formFields.getDisplayValue("programName")%> Registration Site <span id='closed'></span> </h1>
Now in your javascript section:
var now = new Date().getTime(); //Return the number of milliseconds since 1970/01/01:
var epochTimeJul15_1159pm = 1437019199000; // number of milliseconds since 1970/01/01 at Jul 15_11:59:59pm. See http://www.epochconverter.com/.
var timeTillChange = epochTimeJul15_1159pm - now;
function changeHeader(){
document.getElementById('closed').innerHTML = ' is now closed.'; //change the html/text inside of the span with the id closed'.
}
setTimeout(changeHeader, timeTillChange); //will wait to call changeHeader function until timeTillChange milliseconds have occured.
This will make the header get edited live as soon as the clock hits 11:59:59.
if ($.now >= dateLimit){
$("#header1").hide(0);
$("#header2").show(0);
}
This would be a general jquery way to do this, you could setup the two elements to be hidden or shown accordingly in your css.
This would do it upon page load, I am not exactly sure how to implement a dynamic version of this.
That's how you can do dynamically with JavaScript. Working Plunker
You can just compare two date and change innerHTML of header.
<html>
<head>
<script>
function setHeader(){
var d1 = new Date("7/15/15 11:57"); // change your dates here
var d2 = new Date("7/15/15 11:58"); // change your dates here
var header = document.getElementById("header");
if(d1 > d2){
header.innerHTML = "Welcome to the " + <%=formFields.getDisplayValue("programName")%> + " Registration Site."
} else {
header.innerHTML = "Welcome to the " + <%=formFields.getDisplayValue("programName")%> + " Registration Site, is now closed. "
}
}
</script>
</head>
<body onload="setHeader()">
<h1 id="header" class="loginhead"></h1>
</body>
</html>

javascript function is adding data to screen but then being overridden by another function

My issue is related a function being invoked when a page is loaded, which removes the data returned by another function.
My issue
After an order is placed, the user inputs how much they wish to pay, following which their change will be calculated and displayed on the screen. I am able to see the amount of change due when I console.log(pay - rounded_total) (See JS code at end of post below).
However when I try change the div as opposed to logging to the console document.getElementById('change_due').innerHTML = (pay - rounded_total); it only remains on the screen for a matter of milliseconds before it disappears when the GET request is made again. I am sure this is because a get request is being triggered each time the document has loaded, so ideally I am wondering how best to structure my code to deal with this. I have played around with the code I currently have in every possible way at this stage, but still cannot fix the issue.
I am also aware that my class names should not begin with numbers, however my aim with this program is to improve my vanilla javascript, and get to terms with scope etc. in JS.
My code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<ul id="orderList">
<p class="4.75">Cafe Latte price = 4.75</p>
<p class="4.75">Flat White price = 4.75</p>
<p class="3.85">Cappucino price = 3.85</p>
</ul>
<div id="total_paid">Amount due: $0.00</div>
<div id="change_due"></div>
<form onsubmit="changeDue()">
<input type="text" id="uniqueID" />
<input type="submit">
</form>
<script src="js/getData.js"></script>
</body>
</html>
My JS code is as follows:
var rounded_total;
var change;
document.addEventListener("DOMContentLoaded", function(event) {
loadJSONDoc();
});
function loadJSONDoc()
{
var answer;
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
answer = JSON.parse(xmlhttp.responseText)
var items = answer[0].prices[0];
var total = 0;
for(var index in items) {
var node = document.getElementById("orderList");
var p = document.createElement('p');
var price = items[index];
p.setAttribute("class", price)
var textnode = document.createTextNode(index + " price = $" + price);
p.appendChild(textnode);
node.appendChild(p);
};
}
var total = 0;
var update = document.getElementsByTagName("p");
for(var i=0; i< update.length; ++i) {
update[i].onclick = function() {
var num = parseFloat(this.className).toFixed(2);
num = parseFloat(num)
total += num;
rounded_total = Math.round(total*100)/100;
document.getElementById("total_paid").innerHTML = rounded_total;
}
}
}
xmlhttp.open("GET","/items",true);
xmlhttp.send();
}
function changeDue(){
var pay = document.getElementById('uniqueID').value;
document.getElementById('change_due').innerHTML = (pay - rounded_total);
};
Again, to be clear on what I looking to implement, is that when a user has chosen their desired items, they then enter an amount into the input box, following which they submit will provide the amount of change due.
Any help on this would be greatly appreciated.
Thanks, Paul
There are different ways to fix this. But i am not able to understand as why you are using form post here and that too without the url?
you can update
function changeDue(){
...
return false; // this is avoid form submission
}
or
function changeDue(event){
...
// you can also use event.preventDefault() or stopPropagation() here. one of them should work.
}
But again both will stop the form from getting submitted to the server. When you will submit the form to the server, the current page will be refreshed and output of the form request will be displayed on the screen. Thats the reason why you are seeing it for a fraction of second. because your code updates the div and then form submit refreshes the page.
I really suggest you from good will nothing personal. Try to rewrite your code as I understand You are trying to success something with very very wrong structure.
Anyway You can try this or something similar...
function stopPost()
{
if (//something - you can skip if clause)
{
event.preventDefault();
return false;
}
}

Creating a page that requires the user to answer a math equation before opening the home page

So I'm trying to make my index.html be a page that asks the user a question before allowing him/her to access home.html. (The fact that the user could simply open up site_name.com/home is something I'll deal with later lol. Bear with me for now).
Here's my game plan:
When the user opens the page, a random arithmetic question will be pasted into a div. The arithmetic question will be 2 single-digit positive integers and one of the binary operations +, - or *. The answer somehow needs to be stored as a global variable (This is one of the things I'm stuck on). I've constructed the following function for that purpose.
var randquest = function ()
{
var ops = ["+", "-", "*"];
var num1 = Math.floor(Math.rand() * 10);
var num2 = Math.floor(Math.rand() * 10);
var thisOp = ops[Math.floor(Math.rand() * 10) % 3];
var myDiv = document.getElementById("questiondiv");
var myNewNode = document.createElement('div class="outerdiv" id="questiondiv"')
var myContent = document.createTextNode("<p><b>Question:</b> " + num1 + " " + thisOp + " " + num2 + "</p>");
var myNewNode.appendChild(myContent);
var myDiv.appendChild(myNewNode);
answer = new String();
switch (thisOp)
{
case "+"
{
answer = (num1 + num2).toString();
}
case "-"
{
answer = (num1 - num2).toString();
}
case "*"
{
answer = (num1 * num2).toString();
}
}
}
Then, I need a function to check that what a user inputs into the input text cell with id ans is the correct answer to the question that was generated.
var checker = function()
{
var ipt = document.getElementById("ans").value;
if (ipt != answer)
{
alert("Wrong answer. Entrance not granted.");
return;
}
else
{
// Open up home.html
}
}
But for that to work, I somehow need answer to have been a global variable, and I somehow need a procedure inside the else statement that opens up home.html. How do I do this? I'm at a roadblock.
Here's the whole page thus far, if you care to see it:
<html>
<head>
<title>
Sentinel page
</title>
<style type="text/css">
body
{
}
.innerdiv
{
z-index: -1;
position: absolute;
top: 0px;
left: 0px;
width: 700px;
}
.outerdiv
{
width: 700px;
border: 2px solid #FFF;
padding: 10px;
margin: 5px;
text-color: blue;
}
.outerdiv:nth-of-type(2n+0)
{
background: grey;
}
.outerdiv:nth-of-type(2n+1)
{
background: #FFFFCC;
}
#headerdiv
{
text-align: center;
}
#maindiv
{
}
#footerdiv
{
}
p
{
color: blue;
}
h1
{
color: red;
text-shadow: 2px 2px white;
}
</style>
<script>
var randquest = function ()
{
var ops = ["+", "-", "*"];
var num1 = Math.floor(Math.rand() * 10);
var num2 = Math.floor(Math.rand() * 10);
var thisOp = ops[Math.floor(Math.rand() * 10) % 3];
var myDiv = document.getElementById("questiondiv");
var myNewNode = document.createElement('div class="outerdiv" id="questiondiv"')
var myContent = document.createTextNode("<p><b>Question:</b> " + num1 + " " + thisOp + " " + num2 + "</p>");
var myNewNode.appendChild(myContent);
var myDiv.appendChild(myNewNode);
answer = new String();
switch (thisOp)
{
case "+"
{
answer = (num1 + num2).toString();
}
case "-"
{
answer = (num1 - num2).toString();
}
case "*"
{
answer = (num1 * num2).toString();
}
}
}
var checker = function()
{
var ipt = document.getElementById("ans").value;
if (ipt != answer)
{
alert("Wrong answer. Entrance not granted.");
return;
}
else
{
// Open up home.html
}
}
</script>
</head>
<body>
<div class="innerdiv">
</div>
<div class="outerdiv" id="headerdiv">
<h1>my_site</h1>
</div>
<div class="outerdiv" id="introdiv">
<p>Welcome to my site. Before you can enter the main page, I need to make sure you're human. So please answer the question below.</p>
</div>
<div class="outerdiv" id="questiondiv">
<!-- Div to house the arithmetic quesiton -->
</div>
<div class="outerdiv" id="answerdiv">
<p><b>Answer:</b></p> <input type="text" id="ans"> <input type="button" value="Submit" onclick="checker">
</div>
<div class="outerdiv" id="footerdiv">
<p>Last modified: 03/31/2014</p>
</div>
</body>
</html>
If you use JavaScript, you risk people being able to use developer tools to find the answer to use an automated system to get in. Just because a user can't see the answer doesn't mean it's not in the HTML code. The browser has access to this answer, and a bot attempting to get into the site will also have access to it. If you hit the F12 key in Internet Explorer, you'll get developer tools, including a DOM explorer, which will give you access to the entire page in raw HTML code.
You should use something like PHP for this situation. PHP is much easier for printing elements and text than JavaScript, and it's server-side, so code is executed on the web server. Here's how you should set it up.
When the user goes to the website for the first time, the server will redirect to the page captcha.php. Pages other than index.php (the home page, I'm assuming) should also redirect to captcha.php if they haven't answered the question. This pagehas the random math problem generated by PHP, and the <form> uses two POST variables: the answer to the problem, and a unique CAPTCHA code for each question, which is in the <form> already through an <input type="hidden"> tag. PHP can put this unique CAPTCHA session code into the value attribute without JavaScript. When the question is answered, the browser should go to a page to check the answer (ex. captcha_check.php).
Example captcha.php page:
<p>Math problem generated by PHP</p>
<form action="captcha_check.php" method="post">
<input type="hidden" name="captcha-id" value="CAPTCHA code generated by PHP" />
<input type="text" name="captcha-solution" />
<input type="submit" value="Continue" />
</form>
The captcha_check.php page should use the CAPTCHA session code and solution sent to it by POST to check, and redirect to the captcha.php page is the answer is wrong, or redirect to the index.php page otherwise. Before redirecting to the index.php page if the answer is correct, the captcha_check.php page should store a cookie for the session. This way, the cookie is sent to all pages in the HTTP headers, so every page can verify the session. The cookie can remain on the computer forever if you'd like, letting the user visit multiple sessions without the burden.
In general, math problems for CAPTCHAs are not secure, but they're much easier than the standard RECAPTCHAs by Google. If you're looking for a secure CAPTCHA that isn't completely irritating, take a look at PlayThru by areyouahuman.com. http://areyouahuman.com/site-owners/playthru/
Just declare your variable ipt globally, i.e., outside of the function definition.
var ipt;
var checker = function() {
// set ipt value here.
}

Categories