HTML buttons showing text without interrupting the script - javascript

Ok so I'm kind of new in HTML/javascript, but I'm working on a project, which is a text-based game, basically, I want to have a function, which takes an array of text, print the first one in a text zone, and wait until the "ok" button in pressed before printing the next string of the array.this function is in the middle of a bunch of other ones.
Here is my code at the moment:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Retro-Fighting</title>
</head>
<body>
<br><br><br>
<input id="hpPlayer" type="text" value="" size="40" readonly>
<input id="hpBoss" type="text" value="" size="40" readonly>
<div id="sound_element"></div>
<script>
var player={
//Bunch of characteristics
};
var boss={
//Bunch of characteristics
};
var playerTurn=function()
{
var action =prompt("Do you want to : ATTACK , use MAGIC , or drink a POTION?").toLowerCase();
switch(action)
{
case 'attack':
var rand=10+(player.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(player.attack+rand-(boss.defense/2));
alert("You hit "+boss.name+" and deal "+damage+" damage points!" );
boss.hp-=damage;
if(boss.hp<0){boss.hp=0;}
showHp()
break;
case 'magic':
var rand=10+(player.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(player.attackM+rand-(boss.defenseM/2));
alert("You use "+player.magicName1+" on "+boss.name+" and deal "+damage+" damage points!" );
boss.hp-=damage;
if(boss.hp<0){boss.hp=0;}
showHp()
break;
case 'potion':
if(player.potion)
{
var heal = player.luck-Math.floor(Math.random()*20+1);
alert("You drink a potion and restore "+heal+" HP");
player.potion--
player.hp+=heal;
if(player.hp>player.hpMax){player.hp=player.hpMax;}
}
else {
alert("You don't have any potions left!")
playerTurn();
}
showHp()
break;
default:
confirm("You can't do that!");
playerTurn();
}
};
var bossTurn=function()
{
if(Math.floor(Math.random()+0.5))
{
var rand=10+(boss.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(boss.attackM+rand-(player.defenseM/2));
alert(boss.name+" use "+boss.magicName+" and deal "+damage+" damage points!" );
player.hp-=damage;
if(player.hp<0){player.hp=0;}
}
else
{
var rand=10+(boss.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(boss.attack+rand-(player.defense/2));
alert(boss.name+" hit you and deal "+damage+" damage points!" );
player.hp-=damage;
if(player.hp<0){player.hp=0;}
}
showHp()
};
var startBattle=function()
{
showHp()
while(player.hp>0&&boss.hp>0)
{
if(player.speed>boss.speed)
{
playerTurn();
if(boss.hp)
{bossTurn();}
}
else
{
bossTurn();
if(player.hp)
playerTurn();
}
}
if(player.hp)
{
alert("You won!")
//play victory sound
soundPlay("victory.mp3")
//Go to loot !
alert("Thank you for playing the demo of Retro-fighting!")
}
else
{
alert("You lost...The woodman is now free to destroy the world...")
soundPlay("gameover.mp3")
}
};
var showHp=function()
{
var outputHpPlayer = document.getElementById('hpPlayer')
var outputHpBoss = document.getElementById('hpBoss')
var stringHpPlayer= " "+ player.fName + ": " +player.hp+"/"+player.hpMax+" HP"
outputHpPlayer.value=stringHpPlayer
var stringHpBoss= " "+ boss.name + ": " +boss.hp+"/"+boss.hpMax+" HP"
outputHpBoss.value=stringHpBoss
}
var soundPlay=function(music)
{
document.getElementById("sound_element").innerHTML=
"<embed src="+music+" hidden=true autostart=true loop=false>";
}
confirm("You wake up...");
alert("You're wearing strange green clothes, and a sword is laying down, next to you...");
alert("You pick up the sword...An inscription on the blade say : Link" );
alert("You notice that you are in a dark corridor, a strange woodman is looking at you");
alert("The woodman is attacking you!");
startBattle();
</script>
</body>
</html>
Basically, I just want to get rid of the pop-up showing with the alert() command, while still waiting for a confirmation before showing more text
Since I'm really a beginner in programmation, tell me if my method isn't the right one ect...
Thank you!
PS: English is not my native language, sorry

Is this how your code is originally?
getBoss(//depending on the position o the player)
If so, then there is an error. The comment is extending all the way to the closing parenthesis.

Related

make text disappear after clicking another clickable object

I am making an escape room for my website, I have made a few clickable objects that will display a text. My question is, how do I make text go away after clicking on another clickable item? Everything else in my code works just how I like it except for the text part. Please help
Here is what I have so far.
var hasBluekey = false;
var doorknob = "locked"
var comboLock = "locked"
function tryDoor() {
console.log("You clicked the door");
}
function lookhelp() {
console.log("You clicked on help");
let text = "Who needs help?";
document.getElementById("thehelp").innerHTML = text;
}
function lookClue() {
console.log("You clicked on the clue");
let text = "Hmm, there are letters and numbers circled...";
document.getElementById("theclue").innerHTML = text;
}
function moveTable() {
console.log("You clicked on the table");
let text = "You carefully move away the table with the broken vase";
document.getElementById("thetable").innerHTML = text;
document.getElementById("table").style.display = "none";
}
function tryDoorknob() {
console.log("You clicked the doorknob")
if (hasBluekey == true) {
doorknob = "unlocked";
alert("The doorknob is now unlocked");
checkRoom();
} else {
alert("You need a key");
}
}
function tryComboLock() {
console.log("You clicked the combo lock");
var comboTry = prompt("You enter the combination...");
if (comboTry == "AV70") {
comboLock = "unlocked";
alert("The combination was correct");
checkRoom();
} else {
alert("The combination was incorrect");
}
}
function grabBluekey() {
console.log("You clicked the blue key");
hasBluekey = true;
alert("You picked up the key");
document.getElementById("bluekey").style.display = "none";
}
function checkRoom() {
if (doorknob == "unlocked") {
if (comboLock == "unlocked") {
document.getElementById("next").style.visibility = "visible";
} else {
alert("You push on the door but still need a combination");
}
} else {
alert("You try to turn the door knob but is still locked");
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="room">
<img id="door" src="door1.png" onclick="tryDoor()">
<img id="doorknob" src="doorknob1.png" onclick="tryDoorknob()">
<img id="comboLock" src="comboLock.png" onclick="tryComboLock()">
<img id="bluekey" src="blue_key.png" onclick="grabBluekey()">
<img id="clue" src="clue.png" onclick="lookClue()">
<img id="help" src="help.png" onclick="lookhelp()">
<img id="bloodMark" src="bloodMark.png">
<img id="table" src="table.png" onclick="moveTable()">
<img id="window" src="window.png">
<p id="thehelp"></p>
<p id="theclue">
</P>
<p id="thetable"></p>
</div>
<button id="next" onclick="window.location.href
='room2.html';">Proceed</button>
</body>
</html>
Your request seem impossible with an easy answer because you are displaying the text with console.log() I don't think it is possible to update individual lines of output in the console. It is not mentioned anywhere in the documentation. Your easy way out is to display the message or text in a separate element and update that element with the latest text as required. Here is how your code should look like now.
in your html add this code where you want the message to be displayed and style it however you want
<p id="text_message"></p>
And in your javascript code you should replace the console.log("your message"); to this text_message.innerHTML = "your message";
var hasBluekey = false;
var doorknob = "locked"
var comboLock = "locked"
function tryDoor() {
text_message.innerHTML = "You clicked the door";
}
function lookhelp() {
text_message.innerHTML = "You clicked on help";
let text = "Who needs help?";
document.getElementById("thehelp").innerHTML = text;
}
function lookClue() {
text_message.innerHTML = "You clicked on the clue";
let text = "Hmm, there are letters and numbers circled...";
document.getElementById("theclue").innerHTML = text;
}
function moveTable() {
text_message.innerHTML = "You clicked on the table";
let text = "You carefully move away the table with the broken vase";
document.getElementById("thetable").innerHTML = text;
document.getElementById("table").style.display = "none";
}
function tryDoorknob() {
text_message.innerHTML = "You clicked the doorknob";
if (hasBluekey == true) {
doorknob = "unlocked";
alert("The doorknob is now unlocked");
checkRoom();
} else {
alert("You need a key");
}
}
function tryComboLock() {
text_message.innerHTML = "You clicked the combo lock";
var comboTry = prompt("You enter the combination...");
if (comboTry == "AV70") {
comboLock = "unlocked";
alert("The combination was correct");
checkRoom();
} else {
alert("The combination was incorrect");
}
}
function grabBluekey() {
text_message.innerHTML = "You clicked the blue key";
hasBluekey = true;
alert("You picked up the key");
document.getElementById("bluekey").style.display = "none";
}
function checkRoom() {
if (doorknob == "unlocked") {
if (comboLock == "unlocked") {
document.getElementById("next").style.visibility = "visible";
} else {
alert("You push on the door but still need a combination");
}
} else {
alert("You try to turn the door knob but is still locked");
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p id="text_message" style="background-color:grey;color:white;"></p>
<div id="room">
<img id="door" src="door1.png" onclick="tryDoor()">
<img id="doorknob" src="doorknob1.png" onclick="tryDoorknob()">
<img id="comboLock" src="comboLock.png" onclick="tryComboLock()">
<img id="bluekey" src="blue_key.png" onclick="grabBluekey()">
<img id="clue" src="clue.png" onclick="lookClue()">
<img id="help" src="help.png" onclick="lookhelp()">
<img id="bloodMark" src="bloodMark.png">
<img id="table" src="table.png" onclick="moveTable()">
<img id="window" src="window.png">
<p id="thehelp"></p>
<p id="theclue">
</P>
<p id="thetable"></p>
</div>
<button id="next" onclick="window.location.href
='room2.html';">Proceed</button>
</body>
</html>
You could try to use ANSI escape codes -- they are really useful for formatting text in a terminal after it's been printed. For this you would want to use cursor controls and erase functions. these are from this tutorial, which was very helpful for a project I made a while ago. Not all of them work on every platform (e.g. replit, not sure if anyone actually uses that though) but overall it's a good system.
example:
console.log("normal text");
//bold, red foreground
console.log("\u001B[1;31m");
console.log("edited text");
(example from the tutorial)
I'm bad at making examples, but I found the two aforementioned sections to be good for quick reference. To truly comprehend how to use it, I suggest that you read through the whole thing.

Changing values of DIV buttons using javascript

this is a noob question:
I'm defining a button in HTML like this:
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>
To avoid showing too many buttons I'd like the button to toggle between
value="Select good points"
and
value="Select bad points
So in javascript i'm using
$(".btn-change").on("click", function() {
alert("you pressed the " + nextMark + " button");
switch(nextMark) {
case "bad":
nextMark = "good"
document.getelementsbyclassname("btn-change").value="Select good points";
break;
case 'good':
nextMark = "bad"
$("btn-change").value = "Select bad points";
break;
}
}
The nextMark var changes the colour of marks placed on a leaflet map depending on the value of the button.
The alert shows the case structure is working but the button value isn't changing - what is the correct way of doing this?
jsfiddle right here
To assign a value to the input using JQuery you need to use .val() and not .value
var nextMark = "good";
$(".btn-change").on("click", function() {
switch (nextMark) {
case "bad":
nextMark = "good";
$(".btn-change").val("Select good points");
break;
case 'good':
nextMark = "bad";
$(".btn-change").val("Select bad points");
break;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>
You need to specify index to document.getElementsByClassName("btn-change")[0].value = as 0
var nextMark = "good";
$(function(){
$(".btn-change").on("click", function() {
alert("you pressed the " + nextMark + " button");
switch(nextMark) {
case "bad":
nextMark = "good"
document.getElementsByClassName("btn-change")[0].value = "Select good points";
break;
case 'good':
nextMark = "bad"
document.getElementsByClassName("btn-change")[0].value = "Select bad points";
break;
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>
First, you're missing an ending ); to close of the … .on("click" ….
If you are using jQuery, you need to remember to include that first (at the top in <head>), then you should define the JavaScript sheet later. Common practice is at the end, right before the </body> tag.
<script type="text/javascript" src="js.js"></script>
</body>
Next, for the alert, nextMark is not defined.
You can do that with this. when using jQuery, you should keep to it, so use $(this).
Put this inside the function to define nextMark:
var nextMark = $(this);
Once that is done, you need to get the value of it, unless it will say you pressed the [object Object] button. You do that by adding .val() at the end of the target with jQuery; so nextMark.val() inside the alert.
Now to make it switch, you could use a simple if-else statement to switch between the two with:
if (nextMark.val() == "Select good points") {
nextMark.val("Select bad points");
} else {
nextMark.val("Select good points");
}
If you want to use switch, then at least to make it work you need to give it what case it is. What goes inside the (…) of the switch is the case it will use to check.
If I put switch(x) and define x as var x = 1 or var x = "one, we will use this to decide which case to use:
case 1: or case "one": will be executed.
var x = 1;
var y = "one";
switch(y) {
case 1:
// "y" is not 1.
break;
case "one":
// "y" is "one", so this will be exectuted.
break;
}
Therefore, we need to define when the button is "good" or "bad". You could do this by using the literal value, like:
var myMark = $(this).val();
switch(myMark) {
case "Select bad points":
$(this).val("Select good points");
break;
case 'Select good points':
$(this).val("Select bad points");
break;
}
$(".btn-change").on("click", function() {
var nextMark = $(this);
alert("you pressed the " + nextMark.val() + " button");
/* Optional method: */
// if (nextMark.val() == "Select good points") {
// nextMark.val("Select bad points");
// } else {
// nextMark.val("Select good points");
// }
var myMark = $(this).val(); /* or var myMark = nextMark.val(); */
switch(myMark) {
case "Select bad points":
$(this).val("Select good points");
break;
case 'Select good points':
$(this).val("Select bad points");
break;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- jQuery included in this example to make it work -->
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>

How to reset a page, and how to score a win in hangman

So I have my hangman page essentially working, but Im looking to tweak it.
Firstly, my failed guesses are adding up correctly, and the alert pops up when you reach 6 failed try's. The problem im having at the moment is I cant figure out how to reset the page. I've tried some renditions of "$(':reset');" but none have worked for me so far. Currently after the alert pops up you click ok, and then can continue guessing, which is obviously not working as intended.
Secondly, I don't know how to recognize a win in code form. When you play the game, you can guess all the correct letters, but upon guessing the final letter, nothing actually happens. I need to find a way for it to recognize that all letters have been identified.
Thank you ahead of time!
JSfiddle - http://jsfiddle.net/9mxxwu0o/
Html -
<body>
<form id="form" name="form" method="post" action="">
<input type="button" id="but" value="Start"/>
<div id="hangman-jquery">
<div id="word"></div>
<div id="alpha"></div>
</div>
</form>
<div id="win">
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="hangman.js"></script>
</body>
JS -
function hangman(word) {
var trys = 0;
var guess = 0;
var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$.each(alpha.split(''), function(i, val) {
$('#alpha').append($('<span class="guess">' + val + '</span>'));
});
$.each(word.split(''), function(i, val) {
$('#word').append($('<span class="letter" letter="' + val + '">-</span>'));
});
$('.guess').click(function() {
var count = $('#word [letter=' + $(this).text() + ']').each(function() {
$(this).text($(this).attr('letter'));
}).length;
$(this).removeClass('guess').css('color', (count > 0 ? 'green' : 'red')).unbind('click');
if (count > 0) {
$('#win').text("Correct Guess");
} else if (count <= 0) {
trys++;
$('#win').text("You have tried to guess the word and failed " + trys + " times");
}
if (trys == 6) {
alert("You have guessed six times, you lose");
trys = 0;
$("#win").text("");
$(this).val('');
}
});
}
$(document).ready(function() {
$('#but').click(function() {
var options = new Array("DOG", "CAT", "BAT", "HORSE", "TIGER", "LION", "BEAR", "LIGER", "DOOM", "SPIDER", "TREES", "LAPTOP");
var random = 1 + Math.floor(Math.random() * 12);
hangman(options[random]);
});
});
This is where functions come in handy: reusable blocks of code.
Fixed fiddle: http://jsfiddle.net/2azzvscs/
(Scroll down and "Run Snippet" to try it out right inside of stack overflow)
In this case you should move code for starting the game to a separate function (I called it newGame() in example below) that can be called when you need to start a new game after a win or loss.
Also made it detect win condition and ask user to play again.
I also recommend using html() instead of append(); I converted your code to use an array of strings that gets joined into a single DOM fragment that will replace the previous content. Usually, appending to DOM reflows the document, and so you want to do this as little as possible in a loop. (doing it this way also allows your game state to start over without reloading the page from server, which is totally unnecessary in this case).
function hangman(word) {
var trys = 0;
var guess = 0;
var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var strBuilder = [];
$.each(alpha.split(''), function (i, val) {
strBuilder[strBuilder.length] = '<span class="guess">' + val + '</span>';
});
$('#alpha').html(strBuilder.join(''));
strBuilder = [];
$.each(word.split(''), function (i, val) {
strBuilder[strBuilder.length] = '<span class="letter" letter="' + val + '">-</span>';
});
$('#word').html(strBuilder.join(''));
$('.guess').click(function () {
var count = $('#word [letter=' + $(this).text() + ']').each(function () {
$(this).text($(this).attr('letter'));
}).length;
$(this).removeClass('guess').css('color', (count > 0 ? 'green' : 'red')).unbind('click');
if (count > 0) {
$('#win').text("Correct Guess");
} else if (count <= 0) {
trys++;
$('#win').text("You have tried to guess the word and failed " + trys + " times");
}
if ($("#word").text() === word) {
if (window.confirm("You win! Play again?")) {
newGame();
$("#win").text("");
}
}
if (trys == 6) {
alert("You have guessed six times, you lose");
$("#win").text("");
newGame(); // begin new game
}
});
}
function newGame() {
$("#win").text("");
var options = new Array("DOG", "CAT", "BAT", "HORSE", "TIGER", "LION", "BEAR", "LIGER", "DOOM", "SPIDER", "TREES", "LAPTOP");
var random = 1 + Math.floor(Math.random() * 12);
hangman(options[random]);
}
$(document).ready(function () {
$('#but').click(newGame);
});
.guess
{
font-family: "Segoe UI", Arial, Sans-serif;
font-size: 14px;
padding: 5px;
}
.guess:hover
{
background-color: #eee;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body>
<form id="form" name="form" method="post" action="">
<input type="button" id="but" value="Start" />
<div id="hangman-jquery">
<div id="word"></div>
<div id="alpha"></div>
</div>
</form>
<div id="win"></div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="hangman.js"></script>
</body>
Just add this after your loose message:
$("#word, #alpha").html("");
Like this:
if (trys == 6) {
alert("You have guessed six times, you lose");
$("#word, #alpha").html(""); // This
trys = 0;
$("#win").text("");
$(this).val('');
}
Here is WORKING code:
http://jsfiddle.net/9mxxwu0o/3/
I just added couple easy things to it, no tinkering or making it run bit faster, if you want that, then nothingisnecessary provided you an great answer.
Perhaps you could simply reload the page to reset the game?
location.reload();

Looping through array using a button

Ok, in essence I want to create a short quiz that has a next and previous button. I want to loop through two arrays, questions and choices, and have a score at the end. I have read chapters on the DOM and Events and it is just not clicking apparently.
Really I need a little bit of code that shows a concrete example of how to manipulate the DOM. What I have so far are only the arrays, and a function declaring that x is in fact getting my element by id. haha.
Sorry I don't have more code to give. I tried to attach the id to a paragraph, and then get it by it's id and document.write the array, but that replaces the button. If you run the code below you'll see what I'm saying.
<!DOCTYPE html>
<html>
<head>
<title>Bom</title>
</head>
<body>
<input type="button" value="Iterate" id="myButton" onclick="iter_onclick()">
<p id="qArray">Some Text</p>
<script>
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","","The Smurf Girl"]];
function iter_onclick () {
var x = document.getElementById("qArray");
document.write("Hello World");
}
</script>
</body>
</html>`
Like I said, this is my first attempt at truly manipulating the DOM, and I know what I want to do. I just don't know how to do it. I am understanding all the syntax and events and objects and such. But, I'm not really sure how to apply it. Also, no Jquery. I want to know how to create applications with Javascript and then work my way into Jquery. Thanks people.
This will loop through your questions, hope this helps you to proceed.
var qArray = ["Who is my dog?",
"who is the prez?",
"Who is my girlfriend?",
"Who am I?"];
var cArray = [
["Bill", "Billy", "Arnold", "Tyler"],
["Oz", " Buffon", "Tupac", "Amy"],
["Tony Blair", "Brack Osama", "Barack Obama", "Little Arlo"],
["Emma Stone", "Tony the Tiger", "Amy Dahlquist", "The Smurf Girl"]
];
var index = 0;
function iter_onclick() {
//if this is the last question hide and displays quiz ends
if (index >= qArray.length) {
document.getElementById('qArray').innerHTML = '<div>Quiz End, Thank you</div>'
document.getElementById('myButton').style.visibility = 'hidden ';
return false;
}
var html = ' <div> ' + qArray[index] + ' </div> <div>';
for (var i = 0; i < cArray[index].length; i++) {
html += '<label><input type="radio" name="ans" value="'
+ cArray[index][i] + '"/ > ' + cArray[index][i] + ' </label>';
}
html += '</div > ';
document.getElementById('qArray').innerHTML = html;
index++;
}
Here's a very basic example you can work from. This modifies the existing DOM items. You cannot use document.write() on a document that is already loaded or it will clear everything you have and start over and it's not the most efficient way to put content into the DOM.
This example has a number of fields on the page, it loads a question and then checks the answer when you press the next button.
HTML:
<div id="question"></div>
<input id="answer" type="text"><br><br>
<button id="next">Next</button> <br><br><br>
Number Correct So Far: <span id="numCorrect">0</span>
Javascript (in script tag):
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","Amy Dahlquist","The Smurf Girl"]];
var questionNum = -1;
var numCorrect = 0;
function loadQuestion() {
++questionNum;
if (questionNum >= qArray.length) {
alert("all questions are done");
} else {
document.getElementById("question").innerHTML = qArray[questionNum];
document.getElementById("answer").value = "";
}
}
loadQuestion();
function checkAnswer() {
var answer = document.getElementById("answer").value.toLowerCase();
var allowedAnswers = cArray[questionNum];
for (var i = 0; i < allowedAnswers.length; i++) {
if (allowedAnswers[i].toLowerCase() == answer) {
return true;
}
}
return false;
}
document.getElementById("next").addEventListener("click", function(e) {
if (checkAnswer()) {
++numCorrect;
document.getElementById("numCorrect").innerHTML = numCorrect;
loadQuestion();
} else {
alert("Answer is not correct");
}
});
Working demo: http://jsfiddle.net/jfriend00/gX2Rm/

Javascript for Zip Code validation

I'm attempting to have Javascript validate a user-entered zip code.
If it is within the list of valid zip codes, it should take them to a new page to schedule an appointment. If the zip code isn't in the listing, it should display a message that says that it isn't covered by the service area and then keep them on the page.
I have it working to where it takes them to the appointment page if it's valid, but it also takes them to the appointment page if it isn't valid.
Would you guys mind helping me figure this out?
Here is the page the Javascript is running on: http://platinumfactoryservice.com/service-area/
Below is the code:
<script type = "text/javascript">
function checkZip() {
var z = document.myform.zip;
var zv = z.value;
if (!/^\d{5}$/.test(zv)) {
alert ("Please enter a valid Zip Code");
document.myform.zip.value = "";
myfield = z; // note myfield must be a global variable
setTimeout('myfield.focus(); myfield.select();' , 10); // to fix bug in Firefox
return false;
}
var codes = [26003,26030,26031,26032,26035,26036,26037,26038,26039,26040,26041,26058,26059,26060,26062,26070,26074,26075,43713,43716,43718,43719,43747,43750,43757,43759,43768,43773,43778,43902,43905,43906,43909,43912,43913,43915,43916,43917,43927,43928,43933,43934,43935,43937,43938,43939,43940,43941,43942,43943,43947,43948,43950,43951,43952,43953,43963,43967,43971,43972,43977,43985,15004,15017,15018,15019,15021,15025,15028,15031,15034,15035,15045,15046,15047,15053,15054,15055,15056,15057,15060,15064,15071,15078,15081,15082,15088,15102,15104,15106,15108,15110,15112,15116,15120,15122,15123,15126,15127,15129,15131,15132,15133,15134,15135,15136,15137,15139,15140,15142,15143,15145,15146,15147,15148,15201,15202,15203,15204,15205,15206,15207,15208,15209,15210,15211,15212,15213,15214,15215,15216,15217,15218,15219,15220,15221,15222,15223,15224,15225,15226,15227,15228,15229,15230,15231,15232,15233,15234,15235,15236,15237,15239,15240,15241,15242,15243,15244,15250,15251,15252,15253,15254,15255,15257,15258,15259,15260,15261,15262,15264,15265,15267,15268,15270,15272,15274,15275,15276,15277,15278,15279,15281,15282,15283,15286,15289,15290,15295,15301,15312,15317,15321,15323,15339,15340,15342,15350,15361,15363,15365,15367,15376,15378,15379,15347,15330,23705,23703,23707,23708,23704,23709,23702,23701,23326,23328,23327,23322,23325,23320,23324,23323,23321,23520,23519,23541,23512,23551,23515,23529,23506,23501,23514,23521,23518,23502,23503,23505,23513,23509,23504,23508,23511,23517,23510,23507,23523,23459,23458,23450,23479,23471,23466,23467,23465,23463,23461,23451,23460,23456,23452,23455,23454,23453,23462,23464,23457,23261,23291,23260,23225,23221,23249,23222,23223,23241,23232,23224,23290,23173,23298,23273,23274,23289,23279,23282,23276,23278,23295,23219,23218,23220,23269,23286,23292,23293,23285,23284,23228,23227,23226,23229,23075,23231,23230,23294,23289,23060,23059,23075,23288,23242,23238,23250,23233,23255,23150,23058,23234,23831,23235,23237,23236,23836,23114,23112,23113,23297,23832,23120,23838,23801,23803,23804,23805,23806,23834,23111,15004,15017,15018,15019,15021,15025,15028,15031,15034,15035,15045,15046,15047,15053,15054,15055,15056,15057,15060,15064,15071,15078,15081,15082,15084,15088,15102,15104,15106,15108,15110,15112,15116,15120,15122,15123,15126,15127,15129,15131,15132,15133,15134,15135,15136,15137,15139,15140,15142,15143,15145,15146,15147,15148,15201,15202,15203,15204,15205,15206,15207,15208,15209,15210,15211,15212,15213,15214,15215,15216,15217,15218,15219,15220,15221,15222,15223,15224,15225,15226,15227,15228,15229,15230,15231,15232,15233,15234,15235,15236,15237,15239,15240,15241,15242,15243,15244,15250,15251,15252,15253,15254,15255,15257,15258,15259,15260,15261,15262,15264,15265,15267,15268,15270,15272,15274,15275,15276,15277,15278,15279,15281,15282,15283,15286,15289,15290,15295,15301,15312,15317,15321,15323,15339,15340,15342,15350,15361,15363,15365,15367,15376,15378,15379,15347,15330,43711,43717,43722,43723,43724,43725,43732,43736,43772,43778,43779,43780,43788,25504,25510,25526,25537,25541,25545,25559,25571,25701,25702,25703,25704,25705,25706,25707,25708,25709,25710,25711,25712,25713,25714,25715,25716,25717,25718,25719,25720,25721,25722,25723,25724,25725,25726,25727,25728,25729,25755,25770,25771,25772,25773,25774,25775,25776,25777,25778,25779,41101,41102,41105,41114,41129,41139,41169,41183,45619,45619,45623,45638,45645,45669,45675,45680,25011,25026,25033,25070,25082,25109,25112,25124,25143,25156,25159,25168,25177,25213,25334,25338,25357,25375,25389,25560,25569,25003,25015,25025,25035,25039,25045,25054,25061,25064,25067,25071,25075,25079,25083,25086,25102,25103,25107,25110,25126,25132,25134,25160,25162,25201,25202,25214,25301,25302,25303,25304,25305,25306,25309,25311,25312,25313,25314,25315,25317,25320,25321,25322,25323,25324,25325,25326,25327,25328,25329,25330,25331,25332,25333,25335,25336,25337,25339,25350,25356,25358,25360,25361,25362,25364,25365,25387,25392,25396,15001,15003,15005,15009,15010,15026,15027,15042,15043,15050,15052,15059,15061,15066,15074,15077,15081,16123,16136,16101,16102,16103,16105,16107,16108,16112,16115,16116,16117,16120,16121,16123,16132,16140,16141,16142,16143,16146,16148,16150,16155,16156,16157,16159,16160,16161,16172,44401,44403,44405,44406,44416,44418,44420,44422,44424,44425,44429,44430,44436,44437,44438,44440,44442,44443,44446,44451,44452,44454,44470,44471,44473,44481,44482,44483,44484,44485,44486,44488,44501,44502,44503,44504,44505,44506,44507,44509,44510,44511,44512,44513,44514,44515,44555,44619,44672,16001,16002,16003,16016,16017,16018,16020,16021,16022,16023,16024,16025,16027,16029,16030,16033,16034,16035,16037,16038,16039,16040,16041,16045,16046,16048,16050,16051,16052,16053,16055,16056,16057,16059,16061,16063,16066,15006,15007,15014,15015,15024,15030,15032,15037,15044,15049,15051,15065,15075,15076,15086,15090,15091,15101,15144,15238,44609,44701,44702,44703,44704,44705,44706,44707,44708,44709,44710,44711,44714,44718,44720,44720,44721,44730,44730,44735,44750,44767,44799,44601,44646,44647,44648,44608,44613,44614,44626,44630,44632,44640,44641,44643,44650,44652,44657,44662,44666,44669,44670,44685,44688,44689,44056,44067,44087,44203,44210,44216,44221,44222,44223,44224,44232,44232,44236,44237,44250,44260,44262,44264,44278,44286,44301,44302,44303,44304,44305,44306,44307,44308,44309,44310,44311,44313,44314,44315,44316,44317,44319,44320,44321,44325,44326,44328,44333,44334,44334,44372,44396,44398,44632,44685,44280,44256,44254,44281,44273,44258,44274,44233,44215,44235,44251,44253,44212,44282,44275,44240]; // add as many zip codes as you like, separated by commas (no comma at the end)
var found = false;
for (var i=0; i<codes.length; i++) {
if (zv == codes[i]) {
found = true;
break;
}
}
if (!found) {
alert("Sorry, the Zip Code " + zv + " is not covered by our business");
return false;
//do nothing
} else {
alert("The Zip Code " + zv + " is covered by our service team. Please press okay to go forward to schedule an appointment");
document.myform.submit();
}
}
</script>
Change onsubmit="checkZip()" to onsubmit="return checkZip()", because right now your form is always submitted.

Categories

Resources