How to get the proper Javascript output for the number pyramid - javascript

I am currently working on a 1/2 pyramid of numbers. I can get the output to total up the line and get everything but the * sign between the numbers. Hoping that someone out there can lend a helping hand. Here is the code that I have completed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Assignment 1</title>
<script>
var num = "";
var match ="";
var size = prompt("Enter the size of the pyramid");
if (size >=1) {
var total="1";
for(var i=1; i<=size; i++)
{
if (i < size){
num = num + i + " "
} if (i==size) {
num =num + i }
total= total * i;
document.write(num + " = "+ total + "<br>");
}
}else {
alert("Please enter a number equal to or greater than 1");
}
var total="1";
</script>
</head>
<body>
<main>
<!-- Will show after the script has run -->
<h1>Assignment 1</h1>
</main>
</body>
</html>
-
I am looking for output like this
1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120
and so on.
Thanks again

You can use a loop like this and make the total time the new iteration value:
var total = 1;
var newList = [];
for(let i=1; i<=5; i++) {
newList.push(i);
total *= i;
console.log(newList.join('*') + '=' + total)
}
Run code snippet output:
1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120

Related

I am having trouble getting my function mygame() to run in my Javascript program

I am creating a wheel of fortune like game where a player may have 10 guesses to guess a hidden word and I am using charAt and for loops for the guessing. When I go to click on the button in my html the program will not run.
function myGame()
{
var name = prompt("What is your name");
document.getElementById("user_name").innerHTML = "Welcome " + name + " to Wheel of Fortune";
const d = new Date();
document.getElementById("today_date").innerHTML = "Today's date is " + d;
var count = 0;
var phrase = "javascriptisneat";
var word = "";
var checkWin = false;
var w_lgth = phrase.length;
var guess;
var correct_guess = false;
for (var i = 0; i < w_lgth; i++)
word = word + "/ ";
document.getElementById("wheel_game").innerHTML = word;
while (checkWin == false && count < 10)
{
correct_guess = false;
guess = prompt("Guess a letter");
for (var j = 0; j < w_lgth; j++)
{
if(guess == phrase.charAT(j))
{
correct_guess = true;
var set = 2 * j;
word = setCharAt(word, set, guess);
}
}
document.getElementById("wheel_game").innerHTML = word;
checkWin = checkWord(phrase, word);
if(checkWin == true)
{
document.getElementById("game_result").innerHTML = ("you are a winner");
else if (checkWin == false)
{
document.getElementById("game_result").innerHTML = ("You Lose");
if(correct_guess == false)
count = count + 1;
}
}
}
function checkWord(phrase, o_word) { var c_word; c_word = o_word; c_word = o_word.replace(/ /g, ""); if(phrase == c_word) return true; else return false; }
function setCharAt(str, index, chr) { if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>CIS 223 Chapter 7 program</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Welcome Player</h1>
<p> Click to begin </p>
<button type="button" onclick="myGame();">Begin</button>
<p id="user_name"> </p> <br>
<p id="today_date"> </p> <br>
<div id="wheel_game"> </div> <br>
<div id ="game_result"> </div>
<script src="myScript.js"></script>
</body>
</html>
I tried commenting out parts of the code to see what will run and what won't and it seems that the program will run up until the first else if that is on line 39. After that though the program will not run. I checked and I should have the curly brackets in the right places and am not missing any. I am using a external JavaScript file but I know this should not matter.
You forgot to close the curly braces at line 37 of the if statement. I closed the curly braces and it worked for me

How to add an animation gif to a javascript program

I am very new to the world of coding and I am in a coding bootcamp learning about JavaScript. We created a number guessing game and I am trying to add an animation that will run after the correct answer is entered. I have googled a few times trying to find the answer, but I was looking to see if there is an easier way. I have included a copy of the program below. If I wanted an animation to appear after the correct answer is entered, how could I do that?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Number Guessing Game</title>
</head>
<body style='background-color:black'>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script>
function runGame() {
let guessString ='';
let guessNumber = 0;
let correct = false;
let numTries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target, numTries);
} while (!correct);
alert('You got it! The number was ' + target + '.\n\nIt took you ' + numTries + ' tries to guess correctly.');
}
function checkGuess(guessNumber, target, numTries) {
let correct = false;
if (isNaN(guessNumber)) {
alert('Alright smarty pants!\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!\n\nGuess Number: ' + numTries + '.');
} else if (guessNumber < target) {
alert('Your number is too small!\n\nGuess Number: ' + numTries + '.');
} else {
correct = true;
}
return correct;
}
</script>
</body>
</html>
To be able do that you need to learn DOM Manipulation.
Here is a simple example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Number Guessing Game</title>
</head>
<body style='background-color:black'>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script>
function runGame() {
let guessString ='';
let guessNumber = 0;
let correct = false;
let numTries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target, numTries);
} while (!correct);
alert('You got it! The number was ' + target + '.\n\nIt took you ' + numTries + ' tries to guess correctly.');
// add your gif to the dom
// create an img element
const img = document.createElement("img")
// set the source of the gif
img.src = "https://i0.wp.com/badbooksgoodtimes.com/wp-content/uploads/2017/12/plankton-correct-gif.gif?fit=400%2C287"
// add the img element to the dom
// in this case we are gonna add it after the 'start game' button, so
// select the button element
const btn = document.querySelector("button")
// insert the img element after the button
btn.parentNode.insertBefore(img, btn.nextSibling);
}
function checkGuess(guessNumber, target, numTries) {
let correct = false;
if (isNaN(guessNumber)) {
alert('Alright smarty pants!\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!\n\nGuess Number: ' + numTries + '.');
} else if (guessNumber < target) {
alert('Your number is too small!\n\nGuess Number: ' + numTries + '.');
} else {
correct = true;
}
return correct;
}
</script>
</body>
</html>
keep going and good luck.

JavaScript function inside HTML display in browser

I have a problem regarding my JavaScript code. I'm trying to output the sum in the browser, but it doesn't work. I tried every way of displaying the message in JavaScript: console.log(), document.write(), document.getElementById(). None of this seems to work. My code looks okay, but it simply won't output anything. Can someone help me, please?
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script type="text/javascript">
var sum = 0;
for(var i = 0; i < 1000; i++){
if(i%3 === 0 || i%5 === 0)
{
sum += i;
}
console.log('The sum is' + " " +sum);
}
</script>
</head>
</html>
This code works fine here. I'm running IE11 and the sum displays in the console with no problem. See the snippet below; nothing has been changed.
Maybe you just need to open the dev console? F12 in IE/Edge, or Settings > Developer Tools > Console in Chrome (I think).
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script type="text/javascript">
var sum = 0;
for (var i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
console.log('The sum is' + " " + sum);
}
</script>
</head>
</html>
If you want to have your code output to the browser window, you could do something like this, where you add the result to the DOM:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
</head>
<body>
<div id='resultsDiv'>
<h3>Results Here:</h3>
</div>
<script type="text/javascript">
var sum = 0;
var resultsDiv = document.getElementById('resultsDiv');
for (var i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
resultsDiv.innerHTML += 'The sum is' + " " + sum + "<br />";
}
</script>
</body>
</html>
Well, you wrote that you want to display in the browser, I assume you mean the viewport
First of all, you need a body tag:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head></head>
<body></body>
</html>
Sure, the Javascript can be inside the HEAD tag, but if you want anything to be displayed, it needs to be inside the BODY tag.
Second, console.log will print the result to the console, if you want to print the sum in the body, you should change the "print" part to something like
document.getElementsByTagName('body').innerHTML = 'The sum is' + " " + sum;
Or
document.getElementById('sum').innerHTML = 'The sum is' + " " + sum;
Where sum will be an id attribute added to the body tag, also, the
<meta charset="UTF-8">
Goes inside the HEAD tag, and last but not least, you are executing the javascript right away and the DOM won't be necessarily loaded, I suggest you create a javascript function to be called onload as an attribute in the body tag.
So, a working implementation could be like this:
function sum(){
var sum = 0;
for (var i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
console.log('The sum is' + " " + sum);
}
document.getElementById('sum').innerHTML = 'The sum is ' + sum
}
<body id="sum" onload="sum()"></body>
The code will look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function sum(){
var sum = 0;
for (var i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
console.log('The sum is' + " " + sum);
}
//document.getElementsByTagName('body').innerHTML = 'The sum is ' + sum
document.getElementById('sum').innerHTML = 'The sum is ' + sum
}
</script>
</head>
<body id="sum" onload="sum()"></body>
</html>

How to Load an Array from a text file in JavaScript?

I am a complete Beginner using Javascripts and simple descriptive solutions would be very helpful. This is completely on one machine, no server available and I just need to do basic stuff using HTML etc.
I have a task wherein I need to provide an option on the browser to Upload a text file (containing numbers separated by a comma) using Mozilla Firefox only, read the uploaded file into an array, perform some computation on that array and then store the array in another text file and provide an option on the web browser to download the output file.
This is what I have done so far.
**********************************
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script src="javaScripts/script.js" type="text/javascript"></script>
<script src="script.js"></script>
<head runat="server">
<title></title>
</head>
<body>
<input type="file" name="input" size="40"/>
<br />
<input id="Button" type="button" value="Average" onclick="CPU_Average()"/>
<br />
<span id="output1"></span>
</body>
</html>
<script id="average" type="text/javascript">
function CPU_Average() {
var output1 = document.getElementById("output1");
output1.innerHTML = "";
var row = 5;
var col = 5;
var size = row*col;
try{
var windowSize = 3;
var i=0,j=0,k=0,p=0,q=0,count=0,limit=1;
var check=0;
var sum=0.0;
var vec1 = new Uint32Array(size);
var vec_op = new Float32Array(size);
for (i=0; i<size; i=i+1) {
vec1[i] = Math.floor(Math.random() * 100); //Random number 0..99
}
output1.innerHTML += "<br>Vector length = " + size;
output1.innerHTML += "<br>Vector1 = ";
for (i = 0; i < size; i = i + 1) {
output1.innerHTML += vec1[i] + ", ";
}
for(k=0;k<size;k=k+1)
{
sum=0.0;
i=Math.floor(k/row);
j=k%row;
count=0;
for(p=i-limit;p<=i+limit;p=p+1)
{
for(q=j-limit;q<=j+limit;q=q+1)
{
if(p>=0 && q>=0)
{
check = ((p*row)+q);
if(check<size && ((q*col)+p)<size)
{
sum = sum+vec1[check];
count=count+1;
}
}
}
}
vec_op[k] = (sum/count);
}
output1.innerHTML += "<br>Result = ";
for (i = 0; i < size; i = i + 1) {
output1.innerHTML += vec_op[i].toFixed(2) + ", ";
}
}
catch(e) {
document.getElementById("output1").innerHTML
+= "<h3>ERROR:</h3><pre style=\"color:red;\">" + e.message + "</pre>";
throw e;
}
}
</script>
***********************
currently I am generating random numbers and storing them in the input array(vec1), but I need to load that array from an input file. Also my output array(vec_op) prints into a text box but I need to write that array in a text file, each element separated by a comma and allow the user to download it.
If I need to use JQuery or Ajax for it then please explain how to add them in the above code.
Thanks.

Javascript - How to get the sum of a checkbox group

I'm trying to get the sum of my checkbox group (from database):
<script type="text/javascript">
$.ajax({
// SOME CODE HERE
$("#permisos01Div").append("<input type='checkbox' name='chk_permisos'
onClick='VerCostoPermiso()' value='"+data[i].costo+"' > " +
data[i].permiso + "<br>");
// SOME CODE HERE
});
function VerCostoPermiso(){
var group = document.getElementById('chk_permisos');
var sum = 0.00;
for (var i=0; i<group.length; i++){
if (group[i].checked == true){
sum = sum + parseFloat(group[i].value);
}
}
alert(sum);
}
</script>
The result should be: Every time i check the box, alert the sum of the total cbs checked.
My code doesn't work, i really don't know where is the problem.
Thank you for answers
It looks like your dont have an ID assigned, but your using getElementById. Try getElementsByName.
Seems you're using jQuery, you also have a name attribute, not an ID:
var sum = 0;
$(":checkbox:checked[name=chk_permisos]").each(function() {
sum += parseFloat(this.value);
});
"chk_permisos" is the value of a name attribute and should be selected with documents.getElementsByName("chk_permisos"):
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function VerCostoPermiso() {
var group = document.getElementsByName("chk_permisos");
var sum = 0.00;
for (var i = 0; i < group.length; i++) {
if (group[i].checked == true) {
sum = sum + parseFloat(group[i].value);
}
}
alert(sum);
}
</script>
</head>
<body>
<div id="permisos01Div">
<input type='checkbox' name='chk_permisos' onClick='VerCostoPermiso()' value='1'>A1<br>
<input type='checkbox' name='chk_permisos' onClick='VerCostoPermiso()' value='10'>B10<br>
<input type='checkbox' name='chk_permisos' onClick='VerCostoPermiso()' value='100'>C100<br>
</div>
</body>
</html>
If there is a checkbox with out a value sometimes it has the value of "on". When you put this through the parseFloat function you get an error. I would add a number check to the if statement.
if (group[i].checked == true && group[i].value*0 == 0);

Categories

Resources