I created a pyramid using JavaScript and below is the code that I tried so far using for loop:
function showPyramid() {
var rows = 5;
var output = '';
for (var i = 1; i <= rows; i++) { //Outer loop
for (var j = 1; j <= i; j++) { //Inner loop
output += '* ';
}
console.log(output);
document.getElementById('result').innerHTML = output;
output = '';
}
}
Pretty basic! But I am trying to bind the result with HTML element, say with div as follows:
document.getElementById('result').innerHTML = output;
Instead it shows five stars in a row rather than the format in JS seeing in the console. Anything that I am missing here?
Full Code:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pyramid</title>
<script>
function showPyramid() {
var rows = 5;
var output = '';
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= i; j++) {
output += '* ';
}
console.log(output);
document.getElementById('result').innerHTML = output;
output = '';
}
}
</script>
</head>
<body onload="showPyramid();">
<h1>Pyramid</h1>
<div id="result"></div>
</body>
Currently, you are resetting the innerHTML at the end of each loop iteration; either use += to append HTML or append all the output together first, then set the innerHTML. Also, you will need to use the <br> tag to create line breaks in HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pyramid</title>
<script>
function showPyramid() {
var rows = 5;
var output = '';
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= i; j++) {
output += '* ';
}
output += "<br/>";
}
document.getElementById('result').innerHTML += output;
}
</script>
</head>
<body onload="showPyramid();">
<h1>Pyramid</h1>
<div id = "result"></div>
</body>
</html>
const result = document.querySelector("#result");
function generatePyramid(max = 5) {
result.innerHTML = "";
const length = 2 * max - 1;
for (let i = 1; i <= max; i++) {
let s = "*".repeat(i).split("").join(" ");
s = s.padStart(
s.length + Math.floor((length - s.length) / 2)
).padEnd(length);
const div = document.createElement("div");
div.innerHTML = s.replace(/\s/g, " ");
result.appendChild(div);
}
}
// generatePyramid(); // base 5 stars
generatePyramid(11); // base 11 stars
// generatePyramid(21); // base 21 stars
<h1>Pyramid</h1>
<div id="result"></div>
Related
I am trying to compare the elements inside my unordered list to the value in the input textbox. If the value in the input text box matches a word in the unordered list I want to do something with that word in the unordered list.
Here is my JavaScript code:
function CheckWordMatch() {
var wordList = document.getElementById("wordSearchTable");
var wordListLi = wordList.getElementsByTagName("li");
var inputBoxText = document.getElementById("pickedLetters");
for (var i = 0; i < wordListLi.length; i++) {
if (inputBoxText.value === wordListLi[i].value) {
wordArray.style.textDecoration = "line-through";
console.log("IT WORKS");
}
}
}
#wordSearchTable is the ID of the unordered list.
#pickedLetters is the ID of the input text box.
Here is the entire javascript code and html code:
var allCells;
var found = false;
window.onload = init;
function init() {
document.querySelectorAll("aside h1")[0].innerHTML = wordSearchTitle;
document.getElementById("wordTable").innerHTML = drawWordSearch(letterGrid, wordGrid);
document.getElementById("wordList").innerHTML = showList(wordArray);
allCells = document.querySelectorAll("table#wordSearchTable td");
for (var i = 0; i < allCells.length; i++) {
allCells[i].addEventListener("mousedown", highlightLetters)
allCells[i].style.cursor = "pointer";
allCells[i].addEventListener("mouseup", removeMouseDown)
}
document.getElementById("pickedLetters").addEventListener('keyup', CheckWordMatch);
//document.getElementById("wordTable").addEventListener("mouseup", CheckWordMatch);
console.log("Hello");
}
/*============================================================*/
function drawWordSearch(letters, words) {
var rowSize = letters.length;
var colSize = letters[0].length;
var htmlCode = "<table id='wordSearchTable'>";
htmlCode += "<caption>Word Search</caption>";
for (var i = 0; i < rowSize; i++) {
htmlCode += "<tr>";
for (var j = 0; j < colSize; j++) {
if (words[i][j] == " ") {
htmlCode += "<td>";
} else {
htmlCode += "<td class='wordCell'>";
}
htmlCode += letters[i][j];
htmlCode += "</td>";
}
htmlCode += "</tr>";
}
htmlCode += "</table>";
return htmlCode;
}
function showList(list) {
var htmlCode = "<ul id='wordSearchList'>";
for (var i = 0; i < list.length; i++) {
htmlCode += "<li>" + list[i] + "</li>";
}
htmlCode += "</ul>";
return htmlCode;
}
function removeMouseDown(e) {
for (var i = 0; i < allCells.length; i++) {
allCells[i].removeEventListener("mouseenter", highlightLetters2)
}
CheckWordMatch();
}
function highlightLetters2(e) {
var inputBoxValue = document.getElementById("pickedLetters");
e.target.style.backgroundColor = "pink";
inputBoxValue.value = inputBoxValue.value + e.target.textContent;
for (var i = 0; i < allCells.length; i++) {
allCells[i].addEventListener("mouseup", removeMouseDown)
}
}
function highlightLetters(e) {
var inputBoxValue = document.getElementById("pickedLetters");
e.target.style.backgroundColor = "pink";
inputBoxValue.value = e.target.textContent;
for (var i = 0; i < allCells.length; i++) {
allCells[i].addEventListener("mouseenter", highlightLetters2)
}
}
function CheckWordMatch(event) {
var inputBoxText = event.target.value;
var wordList = document.getElementById("wordSearchTable");
var wordListLi = wordList.getElementsByTagName("li");
var inputBoxText = document.getElementById("pickedLetters");
for (var i = 0; i < wordListLi.length; i++) {
if (inputBoxText.value === wordListLi[i].textContent) {
wordArray.style.textDecoration = "line-through";
console.log("IT WORKS");
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Word Search</title>
<meta charset="utf-8" />
<link href="p2-layout.css" rel="stylesheet" />
<script src="p2-makeTable.js" async></script>
<script src="p2-wordSearch.js" async></script>
</head>
<body>
<section id="main">
<header><br></header>
<article>
<figure id="wordTable"></figure>
<input type="button" value="Show Solution" id="showSolution" />
</article>
<aside>
<h1 id="wordSearchTitle"></h1>
<input type="text" id="pickedLetters" readonly />
<figure id="wordList"></figure>
</aside>
</section>
</body>
</html>
First you'll need to attach an event listener to the input element #pickedLetters. I used keyup in this example but feel free to pick what suits your use-case best.
document.getElementById("pickedLetters").addEventListener('keyup', CheckWordMatch);
I also fixed some of your sample code. See below with comments:
function CheckWordMatch(event) {
// get the value of the target which is the value of the input element.
var inputBoxText = event.target.value;
var wordList = document.getElementById("wordSearchTable");
var wordListLi = wordList.getElementsByTagName("li");
for (var i = 0; i < wordListLi.length; i++) {
// since you want to compare the value of the input
// element with the value (or text) of the li element,
//you should use textContent or innerText.
if (inputBoxText === wordListLi[i].textContent) {
wordListLi[i].style.textDecoration = "line-through";
console.log("IT WORKS");
}
}
}
// attach an event listener to the input element to trigger your function.
document.getElementById("pickedLetters").addEventListener('keyup', CheckWordMatch);
Alright, in my results for my program the results are displayed in a horizontal list (for e.x, HI,HELLO,HI,HELLO). I am trying to get these results to be in a numbered list from top to bottom.
function button() {
var inputArray = [];
var size = 4;
for (var i = 0; i < size; i++) {
inputArray[i] = prompt('Enter Element ' + (i + 1));
inputArray.sort();
document.getElementById("demo").innerHTML =
inputArray.map(function(x) {
return x.toUpperCase()
});
}
var str = String(inputArray).toUpperCase().split(",");
}
<button onclick="button();">Array</button>
<p id="demo"></p>
https://repl.it/repls/DangerousCloudyNumber
Just use an ordered list (<ol>) instead of a paragraph (<p>) and add list items (<li>) to the values while mapping them:
function button(){
var inputArray = [];
var size = 4;
for(var i=0; i<size; i++) {
inputArray[i] = prompt('Enter Element ' + (i+1));
inputArray.sort();
document.getElementById("demo").innerHTML = inputArray.map(function(x){ return "<li>"+x.toUpperCase()+"</li>"}).join("");
}
var str = String(inputArray).toUpperCase().split(",");
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<meta charset="utf-8">
<title>Program</title>
</head>
<body>
<button onclick="button();">Array</button>
<ol id="demo"></ol>
</body>
</html>
function button(){
var inputArray = [];
var size = 4;
var final_html = "<ol>"
for(var i=0; i<size; i++) {
input = prompt('Enter Element ' + (i+1));
if (input === null) {
document.getElementById("demo").innerHTML = inputArray.map(function(x){
if (x != null) {
final_html = final_html +"<li>"+x.toUpperCase()+"</li>";
}
});
document.getElementById("demo").innerHTML = final_html;
return; //break out of the function early
}else{
inputArray[i] = input;
}
inputArray.sort();
}
}
I m trying to change the img on the cell once i click on it, however that does not happen, an explanation and a solution would be nice.
I am manually setting gBoard[0][0].isFlagged to true, and then clicking the cell, the img does not change.
html
<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<title>Document</title>
<link href="css/game.css" rel="stylesheet">
</head>
<body onload="init()">
<h1>Welcome to minesweeper</h1>
<div class="board-container"></div><button class="restart-Btn" onclick="restartGame(this)">restartGame</button>
<script src="js/utils.js">
</script>
<script src="js/game.js">
</script>
</body>
</html>
script
const TILE = '<img src="/img/tile.png" >'
const TWO = '<img src="/img/2.png" >'
function printMat(mat, selector) {
var strHTML = '<table border="1"><tbody>';
for (var i = 0; i < mat.length; i++) {
strHTML += '<tr>';
for (var j = 0; j < mat[0].length; j++) {
var className = `cell-${i}-${j}`
strHTML +=
`<td class="${className}"
onclick="cellClicked(this, ${i}, ${j})">
<img src="${mat[i][j].image}" >
</td>`
}
strHTML += '</tr>'
}
strHTML += '</tbody></table>';
var elContainer = document.querySelector(selector);
elContainer.innerHTML = strHTML;
}
function createBoard(size) {
var board = []
for (var i = 0; i < size; i++) {
board[i] = []
for (var j = 0; j < size; j++) {
board[i][j] = creatCell()
}
}
return board
}
function creatCell() {
return {
isBomb: false,
isFlagged: false,
isClicked: false,
isOpen: false,
image: "/img/tile.png"
}
}
function cellClicked(elCell, i, j) {
if (gBoard[i][j].image === TILE && gBoard[i][j].isFlagged === true) {
elCell.innerHTML = TWO
}
}
If you check out the cellClicked() function, the first comparison is not right. TILE holds a string with the entire <img>element but gBoard[i][j].image is just the value of the src attribute, so this comparison:
gBoard[i][j].image === TILE
Is really comparing:
'<img src="/img/tile.png" >' === '/img/tile.png'
Which won't ever be true.
I got it to work by setting up a new variable, tileSrc:
const TILE = '<img src="/img/tile.png" >'
const tileSrc = '/img/tile.png';
Then in the conditional in cellClicked(), test against that:
if (gBoard[i][j].image === tileSrc && gBoard[i][j].isFlagged === true)
You can see it working here: Tiles App
Make sure the function is being called in the console.
Without the HTML I can't know for sure this is the issue but I had an issue of images not updating, but then I found out I had to 'force refresh' the image by adding a time stamp.
Maybe try:
function cellClicked(elCell, i, j) {
if (gBoard[i][j].image === TILE && gBoard[i][j].isFlagged === true) {
var timestamp = new Date().getTime();
elCell.innerHTML = TWO + '?' + timestamp
}
}
How can I sort array.length numerically? In this image my numbers generator should be ordered in descending order.
I tried creating a new array with the push function. My code is as follows:
var newArray = [];
newArray.push(myArray.length);
Unfortunately this doesn't work. I'm a beginner in javascript and I haven't been able to find another solution.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="hack.js" defer></script>
</head>
<body>
<div id="demo" style="width: 500px;border: 1px solid black;"></div>
<script>
var myNumbers = '';
for (var i = 10; i <= 40; i++) {
var myArray = [];
for (var j = 2; j < i; j++) {
if (i % j == 0) {
myArray.push(j);
}
}
myNumbers += "<p>" + i + " number of generators = " + myArray.length + '</p>';
}
document.getElementById("demo").innerHTML = myNumbers;
</script>
</body>
</html>
var myNumbers = [];
for (var i = 10; i <= 40; i++) {
var myArray = [];
for (var j = 2; j < i; j++) {
if (i % j == 0) {
myArray.push(j);
}
}
var value = { int: i, length: myArray.length, html:"<p>" + i + " number of generators = " + myArray.length + '</p>' }
myNumbers.push(value);
}
myNumbers.sort(function(a, b){
return b.length - a.length;
});
document.getElementById("demo").innerHTML = myNumbers.map(function(d) { return d['html']; }).join('')
first you can store mappings of numbers and their generator count in an array of objects. Then you can sort this array using a comparator function. The iterate over this array add elements based on this sorted array.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="hack.js" defer></script>
</head>
<body>
<div id="demo" style="width: 500px;border: 1px solid black;"></div>
<script>
var myNumbers = '', myArray = [];
for (var i = 10; i <= 40; i++) {
var count = 0;
for (var j = 2; j < i; j++) {
if (i % j == 0) {
count++;
}
}
myArray.push({number: i, generators: count});
}
myArray.sort(function(a,b){
return b.generators - a.generators;
});
for(var i=0; i<myArray.length; i++)
myNumbers += "<p>" + myArray[i].number + " number of generators = " + myArray[i].generators + '</p>';
document.getElementById("demo").innerHTML = myNumbers;
</script>
</body>
</html>
I have created a table that displays all prime numbers from 2-1013 but it is displaying from the bottom right to the top left and I would like it to display from the top left to the bottom right. How would I achieve this?
<!DOCTYPE HTML Public>
<html>
<head>
<title>Prime Numbers</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body onload='CalcPrime()'>
<script type='text/javascript'>
function CalcPrime() {
var setIt = 0;
var count = 0;
var num = 3;
var primeArray = new Array();
primeArray.unshift(2)
while (count < 169) {
setIt = 0;
var i = 2
while (i < num + 1) {
if (num % i == 0) {
setIt = setIt + 1;
}
i = i + 1
}
if (setIt < 2) {
primeArray.unshift(num);
count = count + 1;
}
num = num + 1;
}
var a;
document.write("<table cols='10' border='1'>");
document.write("<tr><th colspan=10 border='1'>Prime Numbers 2-1013</th></tr>");
for (var it = 0; it < 161; it = it + 10) {
document.write("<tr>");
for (var colm = 0; colm < 10; colm++) {
a = it + colm;
document.write("<td style='border:1px line;padding:10px;'>" + primeArray[a] + "</td>");
}
}
}
</script>
</body>
</html>
If you push your values onto the array instead of unshifting them, that will put them at the end of your array instead of the start. Which would do exactly what you want.
This will get you close. Basically, instead if incrementing your indices, decrement them. Instead of starting with 0, start with the final number and go down to zero. In other words, reverse your loop.
for (var it = 161; it >= 0; it -= 10) {
document.write("<tr>");
for (var colm = 10; colm >= 0; colm--) {
a = it + colm;
document.write("<td style='border:1px line;padding:10px;'>" + primeArray[a] + "</td>");
}
}
It's not perfect yet, but this will get you close for now. I'll edit after I tweak it a bit.
Before writing the table, reverse the primeArray variable by adding:
primeArray = primeArray.reverse();