ok so I understand this is a very basic JS logic but I am trying to replace any document.write() with .innerHTML and I tried it with the code below
function writeTimesTable(num) {
for(let i = 1; i < 10; i++ ) {
let writeString = i + " * " + num + " = ";
writeString = writeString + (i * num);
writeString = writeString + "<br />";
document.write(writeString);
}
}
function newTable() {
for(let i = 1; i <= 10; i++ ) {
let para = document.getElementById("paragraph");
para.innerHTML = writeTimesTable(i)
}
}
I have a div element with the ID of paragraph already. I keep getting undefined when I look at the div#paragraph and the rest of my code outputs under my script tag but not in the div element. What am I doing wrong?
Your function writeTimesTable() needs to return a value. Your writeString string, needs to be concatenated as well, you can do that with += like seen below:
function writeTimesTable(num) {
let writeString = "";
for(let i = 1; i < 10; i++ ) {
writeString += i + " * " + num + " = ";
writeString += writeString + (i * num);
writeString += writeString + "<br />";
}
return writeString
}
Using para.innerHTML = writeTimesTable(i) probably isn't intended, as it will just display the last loop, so you might also want to use += here as well:
para.innerHTML += writeTimesTable(i)
You normally want to avoid document.write because it literally writes out to the document.
I have also taken the liberty of doing the DOM creation off-page during the loop, and just add it to the actual DOM at the end. This means you aren't constantly re-drawing the page while you loop.
This is better than changing your innerHTML = to innerHTML +=, which you would need to do if you wanted to avoid overwriting each previous iteration of the loop.
function writeTimesTable(num) {
for(let i = 1; i < 10; i++ ) {
let writeString = i + " * " + num + " = ";
writeString = writeString + (i * num);
writeString = writeString + "<br />";
return writeString;
}
}
function newTable() {
const inner = document.createElement('div');
for(let i = 1; i <= 10; i++ ) {
const item = document.createElement('div');
item.innerHTML = writeTimesTable(i);
inner.appendChild(item);
}
let para = document.getElementById("paragraph");
para.appendChild(inner);
}
newTable();
<div id="paragraph"></div>
Your newTable() function with the 10 loops is useless. You're doing 10 times the same stuff over a single DOM element.
Don't use document.write...
I'd do it like:
function newTable( num ) {
var HTML = "";
for (var i=1; i <= num; i++) {
HTML += i +" * "+ num +" = "+ (i*num) +"<br>";
}
return HTML; // Return the concatenated HTML
}
document.getElementById("paragraph").innerHTML = newTable(10);
<p id="paragraph">asdasdasd</p>
Or in a super uselessly cryptic ES6 way:
const newTable = n =>
Array(n).fill().map((_,i) =>
`${i+=1} * ${n} = ${i*n}<br>`
).join('');
document.getElementById("paragraph").innerHTML = newTable(10);
<p id="paragraph">asdasdasd</p>
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>");
As I am new to JavaScript, I am a bit confused of using the for loops in JavaScript. I have tried the times table using the below JavaScript code, but I was unsuccessful in creating the times table for 1 to 9, as displayed in the image.
var display = ""; // The table output HTML
for (i = 1; i <= 9; i++) {
var multiplier = 1;
var result = i * 1;
display += multiplier + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
document.getElementById("outputDiv").innerHTML = display;
I tried using nested for loops, but it left me with an error
This is where I have done with a single for loop
https://codepen.io/vbudithi/pen/LgEPwx
I tried to get the output in the below form
THANKS IN ADVANCE
Use nested loop with break line. "< br >"
Working example: https://codepen.io/anon/pen/yRyLje
var display = "";
for( i = 1; i < 10; i++){
for (j = i; j < 10; j++) {
display += i + " * " + j + " = " + j * i+ "\xa0\xa0\xa0\xa0\xa0" ;
}
display +="<br>";
}
document.getElementById("outputDiv").innerHTML = display;
just like NicolasB said, wrapping the loop in another loop
var display = ""; // The table output HTML
for(j = 1; j <= 9; j++) {
for (i = j; i <= 9; i++) {
var result = i * j;
display += j + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
display += "<br>";
}
document.getElementById("outputDiv").innerHTML = display;
I got webpage with JS code that get randomize Object from array and show it's value with Jquery .html() code in some div.
That work great.
When I click on a another page on the website it also look great, but when I click back on the browser, the code what created max the JavaScript Variables and I get the wrong text in the wrong placement
Any Tip what should I look for?
function showMoodaa(size, divID, countshow) {
if (typeof(countshow) === 'undefined')
countshow = 1;
var rndBanner = "";
var htmlcode = "";
if (modaoot[size] != undefined) {
if (countshow > 1) {
var countMoodaa = modaoot[size].length;
if (countMoodaa > countshow) {
countMoodaa = countshow;
}
rndBanner = Math.floor(Math.random() * modaoot[size].length);
for (i = 0; i < countMoodaa; i++) {
if ((rndBanner + i) >= modaoot[size].length) {
htmlcode = htmlcode + (modaoot[size][rndBanner + i - countMoodaa].html);
window.numBanner = window.numBanner + modaoot[size][rndBanner + i - countMoodaa].id + ",";
} else {
htmlcode = htmlcode + (modaoot[size][rndBanner + i].html);
window.numBanner = window.numBanner + modaoot[size][rndBanner + i].id + ",";
}
}
} else {
rndBanner = Math.floor(Math.random() * modaoot[size].length);
window.numBanner = window.numBanner + modaoot[size][rndBanner].id + ",";
htmlcode = modaoot[size][rndBanner].html;
}
} else {
htmlcode = "<!-- no size like this in array-->";
}
$("#" + divID).append(htmlcode);
}
showMoodaa(2, "pos1");
showMoodaa(2, "pos2");
showMoodaa(10, "pos1", 2);
I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}
This is a coin flipping randomizer. I need to print out 10 rows and 20 columns. This is where I am stuck. My code seems to randomize correctly every time I click my button, it displays 20 columns but I cannot seem to get it to print a second row. It may be something simple that I am just not catching. Anything will be appreciated.
Javascript Code
function toss()
{
var heads = "x ";
var tails = "o ";
var rows = 0;
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++)
{
var val = Math.floor( Math.random() * 2 );
if(val === 1)
{
arr[i] = " x";
}
else
{
arr[i] = " y";
}
document.getElementById("results").innerHTML = arr + "<br />";
}
delete arr;
rows++
}
}
HTML:
<html>
<head>
<title>Coin Flip</title>
<script src="Toss.js" type="text/Javascript"></script>
<style>
#results
{
display: block;
}
</style>
</head>
<body>
Push Button to Flip -> <input type="button" onclick="toss()" value=" Flip ">
<span id="results"></span>
</body>
</html>
The problem is you are replacing the entire results output each time you create a row with the new row. You need to append instead of replace. So change this:
document.getElementById("results").innerHTML = arr + "<br />";
To:
document.getElementById("results").innerHTML += arr + "<br />";
You also need to move the append of the result out of the inner for loop! If you leave the append within the for loop, you will see this behavior: http://jsfiddle.net/t1s93Lqz/3/
JSFiddle: http://jsfiddle.net/t1s93Lqz/2/
You are resetting the html inside the element each iteration through the loop
document.getElementById("results").innerHTML = arr + "<br />";
And while you could concatenate innerHTML each iteration to fix this:
document.getElementById("results").innerHTML += arr + "<br />";
This will cause the whole html for that element to be re-rendered. It would be better to either build the html string first and then set the element's innerHTML property or use DOM methods like appendChild/insertAdjacentHTML.
Build string first
var html = "";
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++) {
var val = Math.floor( Math.random() * 2 );
if(val === 1) {
arr[i] = " x";
} else {
arr[i] = " y";
}
}
//moved the concatenation out of the loop
//otherwise you will get a line each as the array is set
html += arr + "<br />";
rows++
}
document.getElementById("results").innerHTML = html;
Using insertAdjacentHTML
var element = document.getElementById("results");
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++) {
var val = Math.floor( Math.random() * 2 );
if(val === 1) {
arr[i] = " x";
} else {
arr[i] = " y";
}
}
element.insertAdjacentHTML('beforeend',arr+"<br />");
rows++
}
Demo
var rows = 0;
var element = document.getElementById("results");
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++) {
var val = Math.floor( Math.random() * 2 );
if(val === 1) {
arr[i] = " x";
} else {
arr[i] = " y";
}
}
element.insertAdjacentHTML('beforeend',arr+"<br />");
rows++
}
<div id="results"></div>
Also note your delete statement won't do anything as delete works on object properties, if you console.log( delete arr ) you will see it will print false
You are only printing the last row. Replace
document.getElementById("results").innerHTML = arr + "<br />";
with
document.getElementById("results").innerHTML += arr + "<br />";