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-->
Related
It gives always answer "Hello City" although i pressed 1 and 2.. what is wrong with the code? what is better to use ? if else statement or switch statement?
anyone can help?
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function number()
{
var number;
number=document.getElementById('m').value;
switch (number)
{
case 1:
day="Hello World";
break;
case 2:
day="Hello Asia";
break;
default :
day="Hello City";
}
document.write(day);
}
</script>
<input type="number" name="" id="m">
<input type="submit" name="Click" onclick="number()">
</body>
</html>
Cast the value explicitely to a number otherwise it will be a string, the Switch statements in Javascript always use strict type checking (===), thus your example will always return the default value.
var number= +document.getElementById('m').value;
What about parse to integer.
var number=parseInt(document.getElementById('m').value)
Switch testing strict quality. So there is used triple equals.
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("")
}
I have a form that takes numbers, and there is a specific (Phone number, or phNo) form element that I want to only accept 7 digits in length (no more, no less). Using Javascript the Idea is:
If element length not equal to 7: true else false
Here is my code:
var phNo = document.getElementsByName('phNo'); //here I try to get
the form value in the form of an object. This is where I think I am going wrong
var phNoString = phNo.toString(); //Not to sure if I need this line or not, read somewhere that .length only works on a string
if(phNoString.length != 7) {
//Do something for false
return;
} else {
//Do something for true
}
<form id="myForm" action="form_action.asp">
First name: <input type="text" name="fName"><br>
Last name: <input type="text" name="lName"><br>
Phone Number: <input type="number" name="phNo" max="7"><br>
Credit Card Number: <input type="number" name="cardNo"><br>
</form>
<input id="submit" type="button"value="Submit"onClick="detailsSubmit()">
var phNoString = phNo.toString();
This line will return [object HTMLInputElement], you need to use phNo.value if you want the value the user typed inside the input.
Not really related to the problem, but <input type="number" name="phNo" max="7"> here the max attribute only means the highest number possible in that input is 7. Using a browser that supports html5 inputs it's giving me an invalid highlight if I try to enter any phone number.
I would change it to a simple text field and use the maxlength attribute, which is probably what you intended;
<input type="text" name="phNo" maxlength="7">
"getElementsByName" returns a collection type, you should be doing like this to read the value from the element.
var phNoString = document.getElementsByName('phNo')[0].value;
if(phNoString.toString().length != 7) {
//Do something for false
return;
} else {
//Do something for true
}
If you did decide to leave it as a number input, you don't need to convert it to a string. Phone Numbers can't start with 0, so the smallest number would be 1000000. If your input has a max of 7, then you can check that the value is greater than that.
var phNoString = document.getElementsByName('phNo')[0].value;
if(var phNoString > 1000000){
// truthy
}else{
// falsey
}
The document.getElementsByName() function is depreciated in HTML5. See note in w3school site. Use document.getElementById() instead and add an ID tag to your phone input control.
Also use input type="tel" for your phone numbers. That way the browsers, especially on mobile devices, know how to correctly display the inputted value on the screen.
Finally, note the use of regular expressions to do a validation check on the inputted phone number. Also, it is important to note, the HTML5 regex validation runs after the JavaScript function executes. Below is a code snippet that you can sink your new developer teeth into:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
Phone Number (format: xxx-xxx-xxxx):: <input type="tel" id="phNo" name="phNo" pattern="^\d{3}-\d{3}-\d{4}$"/><br>
<button type="submit" name="submit" onclick="checkphonelength()">submit</button>
</form>
<script type="text/javascript">
function checkphonelength(){
var phNoStringLength = document.getElementById('phNo').value.length;
if(phNoStringLength === 12) {
alert("true");
return true;
}
alert(false);
return false;
}
</script>
</body>
</html>
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.
So I'm about 10 hours into my programming career; bear with me please.
My attempt to solve the problem of creating a website with an HTML input area and button such that entering a number between 0 and 100 inclusive and clicking the button will take your score and return an alert box with whatever letter grade corresponds to that score is as follows:
First, the .js file
function grade() {
score = document.form1.grade.value;
if (score==100) {alert("Perfect score!");}
else if (score>=90) {alert("You got an A");}
else if (score>=80) {alert("You got a B");}
else if (score>=70) {alert("You got a C");}
else if (score>=60) {alert("You got a D");}
else {alert("Failure.");}
}
And the HTML:
<form name="form1" onsubmit="return false">
<input type="number"
name="grade"
value=""
min="0" max="100">
</form>
<input type="button" value="Grade" onclick="grade()">
I understand that this is at the level of being trivial, but just doing this simple exercise raised a ton of questions for me.
Why does the button not work if I put it within the form tags?
I tried for an unreasonably long time to get the js to work with switch. Is there a way to do it or am I doing it right with several if/else if statements?
When I didn't have onsubmit="return false" pressing enter in the text field basically borked everything, and `onsubmit="grade()" didn't work at all. Is there any way to make it so that when you enter a number (87) and press return it doesn't submit but executes the grade() function?
Any general structural improvements?
For compatibility reasons, grade is set to your input element, which is also named grade.
There is a way, but it would be quite verbose. if statements should be fine here.
Try window.grade(); return false;. The window.grade gets around the fact that plain grade is masked to the input.
You might want to learn about addEventListener. This lets you completely remove the snippets of JavaScript code (eg. onclick="window.grade(); return false;") from the HTML, leading the HTML to be cleaner. You also may want to learn about document.getElementById (which you'd use to replace document.form1.grade, which is a slightly old way of doing things).
Here's an example using addEventListener and getElementById. Have fun learning to program!
To add to icktoofay's fine (and accepted) answer, if's are just fine, but if you wanted to use a switch statement...
switch (true) {
case score == 100: alert("Perfect score!"); break;
case score >= 90: alert("You got an A"); break;
case score >= 80: alert("You got a B"); break;
case score >= 70: alert("You got a C"); break;
case score >= 60: alert("You got a D"); break;
default: alert("Failure."); break;
}
Regarding switch versus a set of if / else if / else: in most programming languages switch is intended only to match on specific values, not to match on comparisons like the greater-thans you need for your grade calculation. In JavaScript there is a way to get around that and use comparisons within the switch but I don't recommend it because the if / else if structure is already perfectly suited to that. So yes, you are doing it right.
Regarding structure, one way to make your code a little bit more flexible would be to have your function return a string that is the grade result instead of displaying it directly with alert(). That way if you later decide you want to do something else with that string instead of alerting it you don't have to change the core function. Also, I'd change it to take the score in as a parameter rather than always just calculating a grade for a specific score field.
Some examples of what I'm talking about are in the following code, noting that this isn't necessarily very good code but since you're so new I don't want to confuse things by introducing too many concepts all at once. Still, it includes some basic function parameter and string concatenation stuff. Let me know if you need an explanation of any of this.
<script>
function calculateGrade(score) {
if (score==100) { return "Perfect score!"; }
else if (score>=90) { return "You got an A"; }
else if (score>=80) { return "You got a B"; }
else if (score>=70) { return "You got a C"; }
else if (score>=60) { return "You got a D"; }
else { return "Failure."; }
}
function alertGrade(elementId) {
var score = document.getElementById(elementId).value;
var grade = calculateGrade(score);
alert("Score of " + score + ": " + grade);
}
function displayResult() {
// an example that calculateGrade's return directly instead
// of storing it in a local variable
document.getElementById('result').value = "1: "
+ calculateGrade(document.getElementById('score1').value)
+ " 2: "
+ calculateGrade(document.getElementById('score2').value);
}
</script>
<form name="form1" onsubmit="return false;">
Score 1: <input type="number" id="score1" name="score" min="0" max="100">
<input type="button" value="Alert Grade 1" onclick="alertGrade('score1')">
<br/>
Score 2: <input type="number" id="score2" name="score" min="0" max="100">
<input type="button" value="Alert Grade 2" onclick="alertGrade('score2')">
<input type="button" value="Display Both Results" onclick="displayResult()">
<input type="text" id="result" value="">
</form>