Once the user guesses the right number I need to ask if the user would like to play again. As it is the loop will just repeat itself but what I need is the prompt box to ask if you would like to play again. If the user replies yes the loop will initiate again until the answer is guessed
<HTML>
<HEAD>
</HEAD>
<BODY
<FORM NAME="testform">
<BR>
<BR>
<BR>
</FORM>
<INPUT id="attempts" TYPE="text" NAME="inputbox" VALUE="" />
<INPUT id="zero" TYPE="button" NAME="resetbox" VALUE="Reset " onclick="reset()" />
<SCRIPT type="text/javascript">
varattempts = 0;
x = Math.round((Math.random()*19))+1;
var tip;
tip=prompt("Do you want to play a game?")
while(tip.charAt(0).toLowerCase() == "y")
{
var Guess;
document.getElementById('attempts').value = 0;
do
{
Guess = prompt("Pick a number between 1 and 20","")
if (Guess === null) break;
document.getElementById('attempts').value = parseInt(document.getElementById('attempts').value)+1
} while (Guess!=x);
if (Guess == x)
{
alert("You guessed right!")
}
}
function reset()
{
varattempts=0;
document.getElementById('attempts').value = 'Attempts: 0';
}
</SCRIPT>
</BODY>
</HTML>
Put your loop inside another loop. Loopedy loop dee doop.
Easiest it to create a function for running an iteration. When that iteration finishes, the function returns and you ask if they want to play again. If so, you call the function again.
Put all your other code in a function named play():
function play() {
// all your other code here
}
// Then call that function in a loop, return true from play() if the user is done
// and doesn't wish to be asked if they want to play again
var done;
do {
done = play();
} while (!done || window.confirm("Do you want to play again?"));
you could put the main bit in a function, then when its time to reset, return false and recall the function depending on the prompt box. if its yes call it if not just do nothing or maybe display some different text?
varattempts = 0;
looks like a mistake
looks like a messed up way to write something simple imo.
Related
I am trying to make a number guessing game I have the basic part of it down but I am trying to manipulate it so that it initially stores a random number and from there the player keeps guessing till they get it right. If I should continue with the switch statement let me know or should i go back to the if/else statement.
<!DOCTYPE html>
<html>
<style>
</style>
<body>
<h1 id="prompt">Can you guess the number I am thinking of?</h1>
<h2 id="prompt2"></h2>
<input id="guess" type="text" value=""> <!--Box for the input-->
<input type="button" value="guess" onclick="numberGuess();"><!--Button
that exacutes the code-->
</body>
<script>
var randomNumber =Math.floor((Math.random()*10)+1)
function numberGuess() {
var number= randomNumber;
var yourGuess=document.getElementById('guess');
switch (guesspart) {
case (yourGuess==randomNumber) :
console.log('Correct');
break;
case (yourGuess!=randomNumber):
console.log('Correct');
break;
default:
console.log(number);
}};
/*if (yourGuess==randomNumber){
document.getElementById('prompt').innerHTML ='You have guessed
Correctly';
}
else (yourGuess!=randomNumber)
document.getElementById('prompt').innerHTML='Sorry the number was
'+randomNumber;
};*/
</script>
</html>
General Answer
For situations where there are two outcomes to the condition (i.e. a correct answer or an incorrect answer), you should use if/else.
In order to for the comparison to work, you must set yourGuess as document.getElementById('guess').value. Right now you're comparing the DOM input to the correct answer (number), which will always fail.
Performance Implications
Using an If/else statement may be more performant, as it does not need to evaluate the condition of yourGuess!=randomNumber. This is true because we know that if they're not equal, they must be unequal.
Heres an example,
if (yourGuess==randomNumber) {
console.log('Correct');
}
else {
console.log('Incorrect');
}
Notice that we're only evaluating the condition of yourGuess==randomNumber, and not yourGuess!=randomNumber also.
No need for that switch statement which could and should be done using a simple if/else.
You need to get the value from the element document.getElementBydId('guess').value
var randomNumber =Math.floor((Math.random()*10)+1)
function numberGuess() {
var number= randomNumber;
var yourGuess=parseInt(document.getElementById('guess').value);
if(yourGuess === randomNumber) {
console.log("Correct");
} else {
console.log("Incorrect");
}
};
<h1 id="prompt">Can you guess the number I am thinking of?</h1>
<h2 id="prompt2"></h2>
<input id="guess" type="text" value=""> <!--Box for the input-->
<input type="button" value="guess" onclick="numberGuess();"><!--Button
that exacutes the code-->
In the following program, for some reason, the for loop runs through once, and then does not repeat. I believe the error is with the bold code. Help is very much appreciated. This is a program used to change a text box to caps, title case, etc. Title case being the first letter of each word capitalized. Thank you.
<html>
<head>
<script type="text/javascript">
function titlize(){
tLength=tBox.box.value.length
character=new Array()
for(i=1; i<tLength+1; i++){
**character[i]=tBox.box.value.slice(i-1,i)**
document.write(character[i])
if(i==1){
character[i]=character[i].toUpperCase()
}else if(character[i-1]==" "){
character[i]=character[i].toUpperCase()
}else{
character[i]=character[i].toLowerCase()
}
document.write(i)
document.write(character[i])
}
}
function upperC (){
toUpperCase(tBox.box.value)
}
function verify (){
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
if(tBox.lowercase.checked){
tBox.box.value=tBox.box.value.toLowerCase()
}
if(tBox.titlecase.checked){
titlize()
}
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
}
</script>
</head>
<body>
<form name="tBox">
<input type="text" name="box" value=""><br>
<input type="checkbox" name="uppercase" onClick=verify(this.form)>Uppercase<br>
<input type="checkbox" name="lowercase" onClick=verify(this.form)>Lowercase<br>
<input type="checkbox" name="titlecase" onClick=verify(this.form)>Titlecase<br>
</form>
</body>
</html>
tBox is your form not your textbox, so trying to get it's value and then the length of that value is not valid. The code needs to access your textbox, so it should be:
// Scan for the first textbox. Give that textbox a unique id to be
// able to write a more specific query.
tLength= document.querySelector("input[type='text']").value.length;
character=new Array()
// Not sure why you were writing: i < tLength +1 as that will
// cause your loop to go one character too far. Remember,
// arrays start from 0 and length starts from 1.
for(i=1; i < tLength; i++){
Lastly, avoid document.write() because if you use it on a document that has finished being parsed, it will cause the entire existing document to be thrown out.
Based on the code above. You have document.write statements in your function, which is causing issues in overwriting your DOM. I've removed those, and that will allow it to function normally. Also, I added tBox.box.value = character.join("") to put the text back into the text box.
https://plnkr.co/edit/qOPIxwH16hJUlj0RFBhv?p=preview
function titlize() {
tLength=tBox.box.value.length;
character=new Array();
for(i=1; i < tLength + 1; i++){
console.log('print')
character[i]= tBox.box.value.slice(i - 1,i)
//document.write(character[i])
if(i==1) {
character[i]=character[i].toUpperCase()
} else if(character[i-1]==" ") {
character[i] = character[i].toUpperCase()
} else {
character[i]=character[i].toLowerCase()
}
console.log(i)
console.log(character[i])
}
tBox.box.value = character.join("")
}
So i was wondering how do i shows the result once someone inputs the letter A.
the problem is it shows up for a few seconds and disapears
here's my code:
function pop(){
var text = document.getElementById('Search_Text').value;
var res = text.split("");
for (var i = 0; i < res.length; i++){
switch(res[i]) {
case "a":
alert("a");
break;
case "A":
document.getElementById("result").innerHTML="C";
break;
}
}
}
<form onsubmit="">
<input type="text" id="Search_Text"></input>
<button type="submit"onclick="pop()">change</button>
</form>
<p id="result"></p>
You have a submit type button inside a <form> tag.
Clicking that button will cause the browser to reload the page.
Since there are many ways to stop this from happening ... One suggestion could be to put return false; inside the onsubmit attribute of the <form> tag:
<form onsubmit="return false;">
I think that's because you are submitting the form and the page reloads. Thats why you see the result only for a few seconds.
Try this:
function pop(event){
event.preventDefault();
var text =document.getElementById('Search_Text').value;
var res = text.split("");
...
}
My hunch is that you've misunderstood the correct use of forms, and that what you're really trying to do is spit out letters individually onto a page after having typed into a text box and clicked the button.
A for loop does everything as fast as the processor will allow it, so if you're rendering to a page, it's going to be pretty fast.
If you want to see things clearly, you'll have to use JavaScript timing events with callbacks. Here's an example:
function pop(){
var text = document.getElementById('Search_Text').value;
var res = text.split("");
var element = document.getElementById("result");
var duration = 500;
showNextLetter();
function showNextLetter () {
if (res.length) {
element.innerHTML += res.shift();
setTimeout(showNextLetter, duration);
}
}
}
<form onsubmit="">
<input type="text" id="Search_Text"></input>
<button type="submit"onclick="pop()">change</button>
</form>
<p id="result"></p>
I have written a large page including a form as my first JavaScript project. I've gotten some help here, so thanks. I am very happy with what I have so far, but I have one last problem I need to deal with.
The code I will submit here is a tester. I have a couple of functions attached to an onClick new window. What happens is user submits form and their info appears in a new window. (My original page is more complicated, of course.) There is one function called askForHelp which shows an alert in the new window if a specific value is entered for 'state' and a very simple validateForm which shows an alert on the parent?? window if values are left blank.
The problem is b/c i have all the functions running onClick, and I realize they run concurrently, the new window opens no matter what the user does (with the alerts showing in their various places).
Based on other similar questions here, I tried adding a return false and return true statements to my conditionals, but this hasn't done anything.
Now I know there are much better ways to do what I am doing here, and that my form validation is basic and weak, but as my first foray into programming, it was very important for me to understand everything I am doing, which I do, as of now.
Can anyone show me how to fix this so the new window only opens if the form validates? I would prefer no jquery or no radical chances to the code, if possible.
I appreciate everyone's input. Here is the code:
<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="utf-8">
<script type="text/javascript">
function newWindow() {
allInfo= open("", "displayWindow");
allInfo.document.open();
allInfo.document.write('<!doctype html><html><head><title>Test</title><meta charset="utf-8"></head><body>');
allInfo.document.write(document.getElementById ('state').value);
allInfo.document.write('<p>' + document.getElementById ('zip').value);
allInfo.document.write('</section></body></html>');
allInfo.document.close();
}
function askForHelp () {
var volunteer = document.getElementById('state').value;
if ((volunteer == "New York") || (volunteer == "NY") || (volunteer == "New Jersey") || (volunteer == "NJ")) {
allInfo.alert("test test test");
return false;
}
else {
return true;
}
}
function validateForm () {
var x = document.getElementById("state").value;
var y = document.getElementById("zip").value;
if (x == null || x == "" || y == null || y == "") {
alert("Please fill out the required fields.");
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<script type="text/javascript">
</script>
<form id="infoForm" method="post" name="infoForm">
<p>State: </p>
<p><input type="text" id="state" placeholder="State or Region"></p>
<p>Zip: </p>
<p><input type="text" id="zip" placeholder="Zip code" required /></p>
<p><input type="button" value="Submit Information" onClick="newWindow(), askForHelp(), validateForm()" ></p>
</form>
</body>
</html>
Instead of doing an onClick with newWindow(), askForHelp(), validateForm()
Why not just do one of them (which you want to check first) and then have the function call the others when ready?
function validateForm () {
var x = document.getElementById("state").value;
var y = document.getElementById("zip").value;
if (x == null || x == "" || y == null || y == "") {
alert("Please fill out the required fields.");
return false;
} else {
newWindow(); //Validation was successful so lets open the new window
}
}
This way you can have only validateForm() trigger on click, and the rest will trigger when they need to. You'll need to add askForHelp() inside of the newWindow function to have that trigger when necessary as well.
This is sort of a shameless plug, but I just wrote an open source JS library that attempts to solve problems like this. I call it "Is".
http://jumpkick-studios.github.io/Is/
It uses the Maybe Monad concept:
http://en.wikibooks.org/wiki/Haskell/Understanding_monads/Maybe
So it would let you solve this problem with more of a Single Responsibility Principle.
var validateState=function(obj){
return (obj.state!=null) //error check here
}
var validateZip=function(obj){
return (obj.zip!=null) //error check here
}
var openWindow=function(){
//do open window stuff
}
var handleError(){
//handle errors here
}
var onClick=function(e){
var form={state:document.getElementById("state").value, zip:document.getElementById("zip").value})
new jumpkick.Is(form)
.is(validateState)
.is(validateZip)
.then(openWindow)
.catch(handleError)
.finally(function(){
//anything else can go here
});
}
ETA: Perhaps an even better way to approach this is to not have a single handle error function, since you may want to display messaging for each wrong field.
So maybe even something like this would work (a little more code though).
var onClick=function(e){
var validInput=true;
var state=document.getElementById("state").value, zip=document.getElementById("zip").value
new jumpkick.Is(state)
.not().isLongerThan(0)
.then(function(){
validInput=false;
//display message for state
});
new jumpkick.Is(zip)
.not().isLongerThan(0)
.then(function(){
validInput=false;
//display message for zip
});
if(validInput) // openWindow
}
The below code is a simple number guessing game.
The function guess() is getting called twice. I am at loss of logic why it's happening.
<!DOCTYPTE html>
<html>
<head><title>Number Guessing Game version 1.0</title></head>
<body>
<form onsubmit="guess();return false;">
<p><h2>I am your host, human. I am thinking of a number between 0 and 100, including both</h2></p>
<p><input type="text" id="inputId" autocomplete="off"></input><button id="submitButton" onclick="guess()">Guess!!</button></p>
<p><span id="msgId"></span></p>
<p>Guesses Remaining:<span id="guessId"></span></p>
</body>
</form>
<script language="javascript">
var doubleRandom = Math.random();
var guessesLeft = parseInt("10");
var intRandom = Math.round((doubleRandom*100));
var spanObj = document.getElementById("msgId");
var guessObj = document.getElementById("guessId");
guessObj.innerHTML=guessesLeft;
function guess()
{
var guessedNumber = document.getElementById("inputId").value;
alert(23);
if(guessedNumber==null || guessedNumber.trim()==''){
spanObj.innerHTML="Type something, human";
return;
}
if(isNaN(guessedNumber)){
spanObj.innerHTML="That better be a number, Human.";
return;
}else{
if(guessedNumber>100){
spanObj.innerHTML="That better be a number between 0 and 100, Human.";
return;
}else{
spanObj.innerHTML="";
}
}
var accurateAnswer = Math.round(guessedNumber);
var difference = guessedNumber-intRandom;
if(difference>45){
spanObj.innerHTML="That's way too high, Human";
return;
}else if(difference<-45){
spanObj.innerHTML="That's way too low, Human";
}else if(difference<=45 && difference>0){
spanObj.innerHTML="That's high, Human";
}else if(difference>=-45 && difference<0 ){
spanObj.innerHTML="That's low, Human";
}else{
spanObj.innerHTML="Bingo!! You got it!! Refresh to play agin.";
}
if(guessesLeft<=0){
spanObj.innerHTML="You have exhausted your number of guesses. Try again. Refreshing game....";
setTimeout("location.reload(true)", 3000);
}
guessesLeft=guessesLeft-1;
guessObj.innerHTML=guessesLeft;
}
</script>
</html>
That's because you are calling it twice: Once in the button's onclick event, and once in the form's onsubmit event. Delete one of them.
Change
<button id="submitButton" onclick="guess()">Guess!!</button>
to
<input type="submit" id="submitButton" value="Guess!!" />
This way, irrespective of if you click the button, hit enter, or use some other method to submit the form, your event will fire, once.
When you are hit the enter button the form is submitted. On form submit you have the function triggering.
What you could do is to make the button submit the form when clicked.
<button onclick="form[0].submit()">guess</button>
If the button is clicked the form is submitted, therefore the function in from submission is called on button click. This works on hitting enter as well. Both way the function is triggered only once.