So I'm currently taking a coding class and am not very well versed in coding. I'm having trouble with a getelementbyid block which isn't writing my looped array for an assignment. Could anyone help me out?
Here's the code:
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById(message).innerHTML = "your name is " + input[n] + "<br>"
document.getElementById(message2).innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
Your variables and your id-s have the same names. By doing getElementbyId(message) you are passing the variables' values instead of the fixed id you gave to your elements.
You need to put the id-s in quotes as follows:
document.getElementById("message")
document.getElementById("message2")
Tested at my end and this is working code
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById('message').innerHTML = "your name is " + input[n] + "<br>"
document.getElementById('message2').innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
error:-
The id of getElementbyId must be in quotes
Make sure your selectors are strings
document.getElementById("message"); not document.getElementById(message);
Make sure you end your lines of code with semi-colons. This is not optional even though the code will attempt to run without them.
Change your output to render your accumulated data - right now you're overwriting your output every time you loop.
Note: I don't know what you're doing with the numerical value inside of the prompt methods (names and grade ) so I didn't touch it.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = [];
var message = " ";
var message2 = " ";
var n = 0;
var i = 1;
var names = n;
var grade = i;
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name " + names)
message += "Your name is " + input[n] + "<br>";
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value) " + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>";
}
document.getElementById("message").innerHTML = message + "<br>";
document.getElementById("message2").innerHTML = message2 + "<br>";
</script>
#SlavicMilk
Below should be sufficient for your assignment:
HTML (index.html):
<h1 style="text-align: center">Name and Grades</h1>
<table>
<thead>
<th>Name</th>
<th>Grade</th>
</thead>
<tbody id="data">
</tbody>
</table>
<script src="script.js"></script>
JS (script.js):
let student = []
for (let i = 0; i < 5; i++) {
student[i] = {
"name": window.prompt(`Enter Name ${i + 1}`),
"grade": window.prompt(`Enter Grade (numerical value) ${i + 1}`)
}
}
document.getElementById('data').innerHTML = student.map(student => {
return `<tr><td>${student.name}</td><td>${student.grade}</td></tr>`
})
Related
I'd like to write a JavaScript program that displays a symmetric histogram like this image:
The program should ask the user to enter the number of bars to print and the character to use to draw the bars. The count of characters in the bar needs to be displayed on the right-side of each bar.
The example showed is when I entered # as the character and 13 as the number.
Here's my code:
var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let text = "";
let symbolNum = symbol;
while (currentNum <= number) {
text += "<br>" + symbolNum + " " + currentNum;
symbolNum += symbol;
currentNum++;
}
document.write(text + "<br>");
And at last, I only can output the following:
I'd like to know what I can do in order to reverse the loop?
Try this
function SymmetricHistogram(){
const size = 10;
let numberX = 0;
let numberY = 0;
for(let i = size; i>=-size; i--) {
for(let j=size; j>=Math.abs(i); j--){
process.stdout.write("#");
}
numberX <=size ? console.log(numberX++) : console.log(--numberY);
}
}
SymmetricHistogram();
Or try the below
https://onecompiler.com/javascript/3x58bqr3h
Two different way for the same result. Not realy clean, but work.
var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let textTOP = "";
let textBOTTOM = "";
let symbolNum = symbol;
while (currentNum <= number) {
textTOP += "<br>" + symbolNum + " " + currentNum;
if (currentNum < number)
textBOTTOM = "<br>" + symbolNum + " " + currentNum + textBOTTOM;
symbolNum += symbol;
currentNum++;
}
document.write(textTOP + textBOTTOM + "<br>");
var symbol = '#';
var number = 13;
var currentNum = 1;
let text = "";
while (currentNum < number * 2) {
if (currentNum <= number) {
let num = currentNum;
text += "<br>" + symbol.repeat(num) + " " + num;
} else {
let num = Math.abs(number * 2 - currentNum);
text += "<br>" + symbol.repeat(num) + " " + num;
}
currentNum++;
}
document.write(text + "<br>");
First I created a version of this which worked where I didn't input the value on the webpage:
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == 3)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
</script>
Then this is the version I'm trying to create where I enter in the input on the webpage, and then the computer tries to guess it, but it's not executing at all or showing anything when I try to debug in the console.
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
document.getElementById("fingersSubmit").onclick = function ()
{
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == numberOfFingers)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
}
I'm a beginner coder so if there is any useful knowledge pertaining to this in addition to showing me the correct code, then I'd greatly appreciate that!
Thanks!
Here's a working version where I tried to stay as close to your original code as possible:
<html>
<body>
<p>Enter in how many fingers (between 0 and 5) you are holding up:</p>
<p>
<input id="fingersInput" type="text" />
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
document.getElementById('fingersSubmit').onclick = function() {
i = 0;
var fingersText = '';
var correctGuesses = 0;
var numberOfFingers = document.getElementById('fingersInput').value;
while (i < 5) {
var computerGuess = Math.floor(Math.random() * 5 + 1);
fingersText += '<p>' + computerGuess + '</p>';
if (computerGuess == numberOfFingers) {
correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById('fingers-game-v2').innerHTML = fingersText;
document.getElementById('computer-guess-results').innerHTML =
'<h3>' +
'Number of times the computer guessed correctly: ' +
'</h3>' +
correctGuesses;
};
</script>
</body>
</html>
The main reason your code wasnt working is because you need to get the input value when the button is clicked (i.e. place it inside the onclick)
The other issue is that you redeclare correctGuesses inside the if block, so you should just remove the var keyword, otherwise you will get NaN
Finally, this isn't strictly a problem with your code, but moving forward you should be aware that numberOfFingers is a string whereas correctGuesses is a number. In your if block, you compare the two values and it works because you used ==, which only checks value. It's typically better practice to use === which is a stricter equality check, comparing both value and type. So moving forward, you might want to make sure to convert numberOfFingers to a number before you do the equality check
for example my toGuess number is 50 and my best lower guess is 48 but I guess 47 and it changes my best lower guess to that 47.
What I mean by this is that I want it not go lower anymore
Same thing with the higher guess
I want it to save/lock my best guess to the closest
'use strict'
var toGuess = Math.floor(Math.random() * (100 + 1));
console.log("To Guess: " + toGuess);
var guess = undefined;
var amount = 0;
var bestHigher = 100;
var bestLower = 0;
var hint = document.getElementById('hint');
var numbers = document.getElementById('numbers');
var lower = document.getElementById('lower');
var higher = document.getElementById('higher');
function GuessDone() {
var put = document.getElementById('number').value;
guess = Number(put);
console.log("Guess: " + guess);
document.getElementById('form').reset();
amount = amount + 1;
console.log("Guesses " + amount);
var numberDif = Number(toGuess) - Number(put);
var bestLower = Number(put) > toGuess;
var bestHigher = Number(put) < toGuess;
if (numberDif > bestLower) {
bestLower = Number(put);
console.log("Lower " + bestLower);
}
if (numberDif < bestHigher) {
bestHigher = Number(put);
console.log("Higher " + bestHigher);
}
if (guess > toGuess) {
hint.innerHTML = "You need to guess lower";
higher.innerHTML = "Best guess above " + bestHigher;
} else if (guess < toGuess) {
hint.innerHTML = "You need to guess higher";
lower.innerHTML = "Best guess below " + bestLower;
} else {
hint.innerHTML = "Congratz, " + toGuess + " was right! Guesses " + amount;
var print = "";
var i;
for (i = 0; i <= toGuess; i++) {
print += i + "<br>";
}
numbers.innerHTML = print;
}
return false;
EDIT
This is my html
<form id="form">
<label for="number">Guess number between 0-100: </label>
<input id="number" type="text" name="number">
<button type="submit">Guess</button>
</form>
<p id="lower"></p>
<p id="higher"></p>
<p id="hint"></p>
<p id="numbers"></p>
<script src="numbergame.js"></script>
FIDDLE
https://jsfiddle.net/d3761nbj/2/
I am beginner at java script. I am trying to write a script that prompts the users to enter 3 numbers and the program count the number of zero, positive and negative integers user inserted. However,When I output to browser, there is not output shown to browser.
here is my Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Counter</title>
<script type="text/javascript">
<!--
var zero =0;
var negative =0;
var positve =0;
var a1 = ["first", "second", "third", "fourth"];
var a2 = [];
var i = 0;
for( x=0; x< a1.length; x++){
a2. push (prompt("Enter " + a1[x]+ " integer\n" + ""));
}
while (i < a2.length)
{
if (a2[i++]== 0)
zero = zero + 1;
else if (a2[i++] < 0)
negative = negative + 1;
else
{
positive = positive + 1;
i ++;
}
}
//-->
</script>
</head>
<body>
<h1> Welcome to Counter System </h1>
<script>
<!--
document.write ("Zeros Numbers entered by the users = " + zero + " <br/>" +
"Positive Numbers entered by the users= " + positive + "<br/> "+
"Negative Numbers entered by the users =" + negative + "<br/>");
//-->
</script>
</body>
I guess the values are not getting printed as they are not present in below script tag as script tags get differentiated on run time. You can do like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Counter</title>
<script type="text/javascript">
<!--
var zero =0;
var negative =0;
var positve =0;
var a1 = ["first", "second", "third", "fourth"];
var a2 = [];
var i = 0;
for( x=0; x< a1.length; x++){
a2. push (prompt("Enter " + a1[x]+ " integer\n" + ""));
}
while (i < a2.length)
{
if (a2[i++]== 0)
zero = zero + 1;
else if (a2[i++] < 0)
negative = negative + 1;
else
{
positive = positive + 1;
i ++;
}
}
<!--
document.write ("Zeros Numbers entered by the users = " + zero + " <br/>" +
"Positive Numbers entered by the users= " + positive + "<br/> "+
"Negative Numbers entered by the users =" + negative + "<br/>");
//-->
//-->
</script>
</head>
<body>
<h1> Welcome to Counter System </h1>
My program needs to consist of a for loop, use both input functions already created ( name and number) and totals need to be acquired. I also need to be able to CANCEL and go to my doc.write where i would input name and number. I also need to give the user another chance to type in their name or number if they accidentally typed in number where letters should be and vise-versa. I think i have majority of the structure right, any help would be greatly appreciated!
function inputName() {
var nameIn = prompt("Enter your Name");
while(!isNaN(nameIn)) {
nameIn = prompt("Must contain only letters");
}
return nameIn;
}
/* INPUT NUMBER */
function inputNum(){
var numIn=parseFloat(prompt("Enter the number of hours worked \n 0-60 hours"));
var min=0;
var max=60;
while(numIn>min && numIn>max ){
numIn=prompt("Enter a valid number between 0-60");
return numIn;
}
</script>
<body>
<script type="text/javascript">
//DECLARATIONS
var wage=10.00;
var earned; // hrsWrked*wage
var totHrsWrked=0;
var totEarning=0;
var BR= "
";
var howMany;
var loopControl;
//INPUT & PROCESSING
howMany=parseFloat(prompt("How many employees are you inputing?"));
for(loopControl=1 ; loopControl <= howMany; ++loopControl){
var inpNam=inputName();
var inpNumber=inputNum();
earned= inpNumber*wage;
totEarning+=earned;
totHrsWrked+=inpNumber;
//OUTPUT
document.write("Name: "+ inpNam+ BR);
document.write("Hours Worked: " + inpNumber + BR);
document.write("Money Earned: $ " + earned + BR +BR);
}
document.write("Total Hours Worked: " + totHrsWrked.toFixed(2) + BR);
document.write("Total Earnings: " + "$"+totEarning.toFixed(2)+ BR+BR);
</script>
</body>
</html>
Here's the edited version of your code. :)
<! doctype html>
<html>
<body>
<script>
//DECLARATIONS
var wage=10.00, earned, totHrsWrked=0, totEarning=0, howMany;
//INPUT & PROCESSING
howMany=parseFloat(prompt("No of employees"));
for( var loopControl=1 ; loopControl <= howMany; ++loopControl)
{
var inpNam=inputName();
var inpNumber=inputNum();
earned= inpNumber*wage;
totEarning+= (+earned);
totHrsWrked+= (+inpNumber);
//OUTPUT
document.write("Name: "+ inpNam+ "<br>");
document.write("\n Hours Worked: " + inpNumber + "<br>");
document.write("Money Earned: $ " + earned + "<br><br>");
}
document.write("Total Hours Worked: " + totHrsWrked.toFixed(2)+ "<br>");
document.write("Total Earnings: " + "$"+totEarning.toFixed(2)+ "<br>");
//INPUT NAME
function inputName() {
var nameIn = prompt("Enter your Name");
while(!isNaN(nameIn)) {
nameIn = prompt("Must contain only letters");
}
return nameIn;
}
//INPUT NUMBER
function inputNum(){
var numIn=parseFloat(prompt("Enter the number of hours worked \n 0-60 hours"));
var min=0;
var max=60;
while(numIn<=min || numIn>=max ){
numIn=prompt("Enter a valid number between 0-60");
}
return numIn;
}
</script>
</body>
</html>