Ping-Pong aka FizzBuzz test - javascript

I am new to programming and am currently stuck on the Ping-Pong aka FizzBuzz problem. (Make a webpage where the user is prompted to enter a number and every number up to that number is displayed. However, for multiples of three, the page prints "ping," for multiples of five, the page prints "pong," and for multiples of both three and five (15), the page prints "ping-pong.")
I've checked out other solutions on here (such as this one) and they've been helpful for understanding how to solve it. And I hope my javascript reflects that.
My problem is I'm stuck trying to take the input number from the form I have on the webpage and run it through the javascript, if that makes sense.
I'm pretty sure that part of my javascript is just a conglomeration of throwing everything I had at it, which is not the best. Could anyone check out my code and see what I'm doing wrong here?
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.11.2.js"></script>
<script src="js/scripts.js"></script>
<title>Ping-Pong Test</title>
</head>
<body>
<div class="container">
<h1>Ping Pong Test</h1>
<p>Let's play the Ping-Pong game. The Ping-Pong game is a simple test that involves loops, conditionals, and variables. Enter your number below to start</p>
<form id="start-form">
<label for="input-number">Your number:</label>
<input id="input-number" type="number">
<button type="submit" class="btn">Calculate</button>
</form>
<div id="end-number">
<ul id="results"></ul>
</div>
</div>
</body>
</html>
And my javascript:
$(document).ready(function () {
$("#start-form").submit(function(event) {
var a = document.getElementById("#input-number");
var num = a.elements[0].value;
var listItems = "";
var i;
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
console.log("Ping-Pong");
}
else if (i % 3 === 0) {
console.log("Ping");
}
else if (i % 5 === 0) {
console.log("Pong");
}
else{
console.log(i);
};
event.preventDefault();
};
});
Again, I'm new, so if anyone could break it down step by step, I'd really appreciate it. Thanks.

It is not right:
var a = document.getElementById("#input-number");
Must be one of the below lines:
var a = document.getElementById("input-number");
// Or
var a = $("#input-number").get(0);
// Or
var a = $("#input-number")[0];
But it will not solve your problem. Looking deep into your code. I guess you need to have a form an then get the first element:
var a = document.getElementById("start-form");
var num = a.elements[0].value;
But you can simplify even more. Why not just do it:
// remove the a variable
var num = $("#input-number").val(); // get the input-number value

Based on your code I think you just need some syntax cleaned up in order for jquery to use the value from your form.
I took your code, stripped it down for clarity and made a fiddle out of it.
Here is the link:
http://jsfiddle.net/zwa5s3ao/3/
$(document).ready(function(){
$("form").submit(function(event){
var num = $('#input-number').val()
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
$('#list').append('<li>'+"Ping-Pong"+'</li>');}
else if (i % 3 === 0) {
$('#list').append('<li>'+"Ping"+'</li>');}
else if (i % 5 === 0) {
$('#list').append('<li>'+"Pong"+'</li>');}
else{
$('#list').append('<li>'+i+'</li>');}
};
event.preventDefault();
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Ping-Pong Test</title>
<body>
<form>
Your number:
<input type="number" name="input-number" id="input-number">
<input type="submit" value="Calculate">
</form>
<ul id="list"></ul>
</body>
Hope this helps!

Related

Javascript identical if else statements behaving differently /not outputting HTML

I am new to JS and was trying to practice conditionals when I ran into this really weird problem.
Each conditional is working as intended in the sense that when the desired condition is met, the code is executed, for example, console.log() is outputting exactly what I want it to but trying to output the same to HTML is not working for some reason.
My code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<title>Tester</title>
</head>
<body>
<p id="test"></p>
<script>
const max = 5;
const ranNumber = Math.floor(Math.random() * max) + 1;
console.log(ranNumber);
let correct = false;
while (!correct) {
let guess = prompt("Guess a Number 1 - " + max);
guess = Number(guess);
if (guess === ranNumber) {
correct = true;
$("#test").html("Your guess was correct!");
} else if (guess > ranNumber) {
$("#test").html("Your guess was too high!");
} else {
document.getElementById("test").innerHTML = "Your guess too low!";
}
}
</script>
</body>
</html>
Now, I am using Jquery to write the HTML to the p tag but I also tried it like this:
<!DOCTYPE html>
<html>
<head>
<title>Tester</title>
</head>
<body>
<p id="test"></p>
<script>
const max = 5;
const ranNumber = Math.floor(Math.random() * max) + 1;
console.log(ranNumber);
let correct = false;
while (!correct) {
let guess = prompt("Guess a Number 1 - " + max);
guess = Number(guess);
if (guess === ranNumber) {
correct = true;
document.getElementById("test").innerHTML = "Your guess was correct!";
} else if (guess > ranNumber) {
document.getElementById("test").innerHTML =
"Your guess was too high!";
} else {
document.getElementById("test").innerHTML = "Your guess too low!";
}
}
</script>
</body>
</html>
Your page can't load while you're in the while loop and using prompt halts your javascript until it gets an input. Here's a link to a similar question that was asked:
https://www.reddit.com/r/webdev/comments/p8vod8/very_new_to_js_why_does_the_html_text_not_load/
A much better way which is also pretty easy is using an input field and a button. the onclick option runs your function
<input type="number" id="input">
<button onclick="guess()">Guess</button>
And your javascript can look like this
const max = 5
const ranNumber = Math.floor(Math.random() * max) + 1
console.log(ranNumber)
function guess(){
let input = document.getElementById('input').value
let text = document.getElementById('test')
if(input == ranNumber){
text.innerHTML = "You guessed it!"
}
else{
text.innerHTML = "Wrong!"
}
}
The fact that yr code does work! can be seen in the debugger,
but only that the loop runs to fast that you can't see it,
Congrats, for your use of 'const, Number(),' guess === ranNumber assignment operator given that, you say U are new to JS
So to output it to Html, you would need a little bit of adjustment!

Why isn't this JavaScript code executing?

Sorry, I'm a student and I can't figure out what is wrong with my code! When I click the buttons absolutely nothing happens. I've tried isolating each function and still nothing happens. I've been looking it over for ages trying to find a missing tag or a missing bracket or parentheses or something but I'm not finding it. It's meant to create a mini-blog simulation. You should be able to add an entry to the top of the list with the first function, and you should be able to delete an entry of your choice with the second function. Thank you for any help!
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 5 Activity</title>
<meta charset="UTF-8">
</head>
<body>
<h1>Awesome NBA Blog! Each day, a sentence about the feats of a different legend!</h1>
<ol id="playerEntries">
<li>Michael Jordan: 6 Championship rings in 6 NBA Finals appearances.</li>
<li>Bill Russell: 11 time champion in a 13 year career, including one as a player/head coach.</li>
<li>Kobe Bryant: 5 Championships, 18-time All-Star.</li>
<li>Lebron James: Won a Championship and was the Finals MVP with 3 different teams.</li>
</ol>
<form action="">
Add a new entry:
<input type="text" name="newEntry" id="newEntrySpot" size="80">
<input type="submit" value="Submit" onclick="addEntry()"><br>
Delete an entry(which entry would you like to delete?)
<input type="number" name="entryNum" id="numToDelete">
<input type="button" value="Delete" onclick="deleteEntry()"><br>
</form>
<script type="text/javascript">
function addEntry() {
var newEntry = document.getElementById("newEntrySpot").value;
var newestEntry = document.createElement("li");
newestEntry.innerHTML = newEntry;
var blogList = document.getElementsByTagName("ol")[0];
var topEntry = document.querySelectorAll("#playerEntries li")[0];
blogList.insertBefore(newestEntry, topEntry);
}
function deleteEntry() {
var num2Delete = document.getElementsByName("entryNum")[0].value;
var blogList = document.getElementsByTagName("ol")[0];
var howManyEntries = blogList.length;
if (howManyEntries >= 1) {
var postToDelete = blogList[num2Delete - 1];
var deletedPost = blogList.removeChild(postToDelete);
}
}
</script>
</body>
</html>
You have to replace
<input type="submit" value="Submit" onclick="addEntry()"><br>
with
<input type="button" value="Submit" onclick="addEntry()"><br>
otherwise the form will be submitted and the page will reload. You can also use the submit function of the form but will you have to use preventDefault.
Also to make the deleteEntry function works, you can't use document.getElementsByTagName("ol")[0]; since you can't use .length on an element. Here's another way to do it :
function deleteEntry() {
var num2Delete = document.getElementsByName("entryNum")[0].value;
var blogList = document.querySelectorAll("ol > li");
var howManyEntries = blogList.length;
if (howManyEntries >= 1) {
var postToDelete = blogList[num2Delete - 1];
postToDelete.remove();
}
}

Rewriting the code using % operator instead of if statement

I was working on this code, and I got stuck here as a JS rookie and need help. How would you rewrite this block, using % operator, instead of if statement?
<!DOCTYPE html>
<html>
<head>
<script>
window.onload=function(){
var letters = ["A","B","C"]
var counter = 0;
var timer=setInterval(
function(){
counter= counter+1;
if (counter==letters.length){
counter=0;
}
document.getElementById("demo").value=letters[counter];
},1000)
}
</script>
</head>
<body>
<input type="text" id="demo" value="A">
</body>
</html>
Simple use it after doing your add operation to return the remains after division (or modulus):
const letters = ["A","B","C"]
let counter = 0;
setInterval(function(){
counter = (counter+1) % letters.length;
document.getElementById("demo").value = letters[counter];
}, 1000);
<input type="text" id="demo" value="A" />
Couple of other tips, use const if the values don't change (like your array), and let if it can definitely change. Also, you don't need to store your interval here as you never cancel it, so no need for const timer in that case. Simplifies the code a lot!

JavaScript in HTML code: Random numbers are not evenly distributed

I've got the following problem:
I'm uploading a survey on amazon mturk using Python and the survey is done via HTML and javascript. I show one of three different versions of the survey to participants, which I select by generating a random number via javascript. I store the number in local storage to prevent refreshing the website from resetting it. The problem I find is that more people seem to get versions 1 than version 3. But I cannot recreate the problem for myself when running the code in Tryit Editor online.
Could you please help me understand (and fix) why this happens? The following is the (trimmed) HTML code that I upload. I replaced text and removed fluff.
<HTMLQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2011-11-11/HTMLQuestion.xsd">
<HTMLContent><![CDATA[
<!-- YOUR HTML BEGINS -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/externalHIT_v1.js'></script>
<script>
function test(){
document.getElementById('txt-field').value = "1";
}
</script>
</head>
<body>
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'><input type='hidden' value='' name='assignmentId' id='assignmentId'/>
<span>
<INPUT TYPE="text" NAME="link_click" id='txt-field' value="0" style="display: none">
<div><h3><a href="www.google.com" target="_blank" id='report420' onclick="test()" >link</a></h3>
Instructions</div>
<div><table border="1" style="height: 258px;" width="196"><tbody>Table</tbody></table></div>
</span>
<!--I think the relevant part starts here-->
<script>
document.write("Miscellaneous question");
var i = localStorage.getItem('i') || Math.floor(3*Math.random());
localStorage.setItem('i',i);
if (i==0){
document.write("Version 1");
}
if (i==1){
document.write("Version 2");
}
if (i==2){
document.write("Version 3");
}
document.write("Miscellaneous question");
</script>
<p><input type='submit' id='submitButton' value='Submit' /></p></form>
<script language='Javascript'>turkSetAssignmentID();</script>
</body></html>
<!-- YOUR HTML ENDS -->
]]>
</HTMLContent>
<FrameHeight>600</FrameHeight>
</HTMLQuestion>
The random function Math.floor(3*Math.random()) has uniform distribution, but I don't think that 400 samples are enough so that you can see it in action (as #desoares mentioned).
Testing code:
var count = [0, 0, 0];
var n = 1000000;
document.write('Testing for ' + n + ' samples : ');
for (var i = 0; i < n; i++) {
count[Math.floor(3*Math.random())]++;
}
document.write(JSON.stringify(count));
var count = [0, 0, 0];
var n = 400;
document.write('Testing for ' + n + ' samples : ');
for (var i = 0; i < n; i++) {
count[Math.floor(3*Math.random())]++;
}
document.write(JSON.stringify(count));
Also, if you want to be sure that people from the same computer are not forced to take the same version, you should clear the saved variable localStorage.removeItem('i'); on submit. You may also add an expiration mechanic.

We are analysing some code, I get what it is doing, but there is a line of code which I don't understand

This is the full code:
<html>
<head>
<script type='text/javascript'>
var banners = ["Red.jpg","Amber.jpg","Green.jpg"];
var bnrCntr = 0;
var timer;
function banCycle()
{
if(++bnrCntr == 3)
bnrCntr = 0;
document.images.banner.src = banners[bnrCntr];
timer = setTimeout("banCycle()",1000);
}
function stopCycle()
{
clearTimeout(timer);
}
</script>
</head>
<body>
<img src="Red.jpg" name="banner" width=110 height=200>
<form>
<input type="button" value="Cycle" name="Cycle" onclick="banCycle()">
<input type="button" value="Stop" name="Stop" onclick="stopCycle()">
</form>
</body>
</html>
It is the line that I don't understand:
if(++bnrCntr == 3)
Can anyone tell me what this line does?
The line
if (++bnrCntr == 3)
does the same thing as
if ((bnrCntr += 1) == 3)
or
bnrCntr = bnrCntr + 1;
if (bnrCntr == 3)
The value of bnrCntr is incremented, and the result is then assigned back to the variable. Then the value is compared to 3. The ++ operator is called the prefix increment operator.
It first increases the bnrCntr value by 1 and if that value equals to 3 it's set back to 0. You get circular banner changing this way. You could also write it this way, so it's more understandable:
if (++bnrCntr == banners.length)
bnrCntr = 0;
So, when the index goes out of the bounds of the array, start from the beginning.

Categories

Resources