JavaScript function inside HTML display in browser - javascript

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>

Related

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.

For-Loop with JavaScript, got 1 inc number that not in loop

I am new in JavaScript. I am trying to make a for-loop, I am looking to get an output with the numbers from 1 to 20 each on a new line with the corresponding string attached to it. But, the output is showing number 21. Any advice?
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
<h3>Soal No. 2</h3>
<div id="jawaban2"></div>
<script>
var jawaban2;
for (var jawaban2 = 1; jawaban2 <= 20; jawaban2++) {
if (jawaban2 % 2 === 0) {
document.write(jawaban2 + " = Berkualitas" + ("<br/>"))
} else if (jawaban2 % 3 === 0) {
document.write(jawaban2 + " = I Love Koding" + ("<br/>"))
} else {
document.write(jawaban2 + " = Santai" + ("<br/>"))
}
}
console.log(jawaban2);
document.getElementById("jawaban2").innerHTML = jawaban2
</script>
</body>
</html>
You can do like this
for (let jawaban2 = 1; jawaban2 <= 20; jawaban2++) {
if (jawaban2 % 2 === 0) {
document.write(jawaban2 + " = Berkualitas" + ("<br/>"))
} else if (jawaban2 % 3 === 0) {
document.write(jawaban2 + " = I Love Koding" + ("<br/>"))
} else {
document.write(jawaban2 + " = Santai" + ("<br/>"))
}
if(jawaban2 === 20) {
document.getElementById("jawaban2").innerHTML = jawaban2
}
}
The last iteration (jawaban2 += 1) is executed and jawaban2 now has value 21. The loop re-enters, an now the value reaches the case jawaban2 <= 20. So the loop is ended. But jawaban2 is already executed. That's why printing jawaban2 after the loop shows 21.
You can declare jawaban2 within the loop (for (let jawaban2 = 1; ...).
If you need jawaban2 after the loop however and you want its value to be the maximum of the loop (20), you should first subtract 1 from it before further use.
Or you can use variable scope (see MDN), something like:
let jawaban2 = 20;
for (let jawaban2 = 1; jawaban2 <= 20; jawaban2 += 1) {
// ^ for clarity
if (jawaban2 % 2 === 0) {
console.log(jawaban2 + " = Berkualitas")
} else if (jawaban2 % 3 === 0) {
console.log(jawaban2 + " = I Love Koding")
} else {
console.log(jawaban2 + " = Santai")
}
}
// scope of jawaban2 within the loop is local
// for the loop, so outer jawaban2 is still 20
console.log(jawaban2);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Do it like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
<h3>Soal No. 2</h3>
<div id="jawaban2"></div>
<script>
var content = "";
for (var jawaban2 = 1; jawaban2 <= 20; jawaban2++) {
if (jawaban2 % 2 === 0) {
content += jawaban2 + " = Berkualitas" + "<br/>";
} else if (jawaban2 % 3 === 0) {
content += jawaban2 + " = I Love Koding" + "<br/>";
} else {
content += jawaban2 + " = Santai" + "<br/>";
}
}
document.getElementById("jawaban2").innerHTML = content
</script>
</body>
</html>

How to get the proper Javascript output for the number pyramid

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

The fifteen puzzle game

I am doing a fifteen puzzle game and I want that you only can click on a number next to the empty box, but now you can click everywhere...how to change this? I have thought that you can make an if- statement for columns and rows..
<!DOCTYPE html>
<html>
<head>
<title>The Fifteen Puzzle Game</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var currentBoard = new Array(' ','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15');
for(i=0 ; i++<100 ; x = Math.floor(Math.random()*16), y = Math.floor(Math.random()*16), currentBoard[x] = currentBoard.splice(y, 1, currentBoard[x])[0]);
repaint(); // Redraw puzzle board
//
// Funktion repaint()
// Redraw puzzle board
function repaint(){
currentString = "";
for(i=1;i<17;i++){
currentString += "<input type='button' id='" + i + "' value='" + currentBoard[i-1] + "' />";
if ( (i%4) == 0 ) currentString += "<br />";
}
$("#board").html(currentString);
}
function swapArrElems(index_a, index_b) {
var temp = currentBoard[index_a];
currentBoard[index_a] = currentBoard[index_b];
currentBoard[index_b] = temp;
}
$('#board').click(function(event){
current = $(event.target).attr("id")-1;
for(i=0;i<16;i++) if( currentBoard[i]==0 ) zeroIndex = i;
swapArrElems(current, zeroIndex);
repaint();
});
});
</script>
<style>
input[type="button"] { width: 80px; height: 80px; font-size: 30px; }
</style>
</head>
<body>
<div id="board">
</div>
</body>
</html>
From the way I understood your code, you have 16 buttons id'ed by rows of 4. Each time a button is clicked, the array value of that button and the blank button swap. You're almost there. The detail that is the most important here is the button ID's, which stay the same throughout.
You need to add a comparison between the ID of the clicked button, and that of the blank button, which requires a conditional.
I'm not going to provide the code for you, because I don't want to just give away the answer. I'm going to give you the logic instead:
In your last function, after if( currentBoard[i]==0 ) zeroIndex = i;
**Else if** the id(clicked button) == id(blank button)-1. OR id(blank button)+1. OR
id(blank button)-4. OR id(blank button)+4 ........
Swap the elements.
Else
don't swap the elements.
Good luck! Hope this helps.
for (i = 0; i < 16; i++) {
if (currentBoard[i] == 0) {
if ((i - current) == 4 || (current - i) == 4 || (current - i) == 1 || (i - current) == 1) {
zeroIndex = i;
swapArrElems(current, zeroIndex);
repaint();
}
}
}

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