How to create a bootstrap list group with two arrays? - javascript

I'm currently creating a dashboard and I want to create a "Bootstrap List Group" which should show a list of friends of the current dashboard.
I have given to arrays like this:
friendsID[id1, id2, id3]
friendsName[name1, name2, name3]
I want to create a method in javascript so that the result looks like this.
<div class="list-group">
name1
name2
name3
</div>
Would love to here how you would manage this because I am a little bit desperate and have no clue how to do this.

Here You can use document.write() to solve the problem it is used when the path for the html is not needed
var friendsID = ['id1','id2','id3'];
var i=0;
var friendName = ['name1','name2','name3'];
console.log(friendName[2]);
idplace();
function idplace(){
for(i=0;i<friendsID.length;i++)
{
document.write("<a href='/dashboard/"+friendsID[i]+"' class='list-group-item list-group-item-action'>"+friendName[i]+"</a><br>")
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="./java.js"></script>
</body>
</html>
Or You can Use Innerhtml in this the path inside which div the html must be kept is determined by the programmer.
var friendsID = ['id1','id2','id3'];
var i=0;
var statement =[0,0,0];
var friendName = ['name1','name2','name3'];
console.log(friendName[2]);
idplace();
function idplace(){
for(i=0;i<friendsID.length;i++)
{
statement[i]="<a href='google.com/"+friendsID[i]+"'>"+friendName[i]+"</a><br>";
console.log(statement[i]);
document.getElementById("hello").innerHTML+=statement[i];
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="hello"></div>
<script src="./java.js"></script>
</body>
</html>

You can do something like this
const friendsID = ["id1", "id2", "id3"]
const friendsName = ["name1", "name2", "name3"]
let i = 0;
for (i = 0; i < friendsID.length; i++) {
let list = '' + friendsName[i] + ""
$(".list-group").append(list)
}
<div class="list-group">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

check this out
https://jsfiddle.net/cloud_zero/hacLpe3g/4/
var arry1 = ["name1", "name2", "name3"];
var arry2 = ["id1", "id2", "id3"];
// merging two array
var result = arry1.reduce(function(acc, cur, index) {
return Object.assign(acc, { [arry2[index]]: cur })
}, {})
// generating links
var text = Object.keys(result).map(function(key) {
return `${ result[key] }`;
});
// finally adding to dom
document.querySelector('.list-group').innerHTML = text.join('');
first i merged two array to object (result)
then i generate links from the result
lastly linked added to DOM

First of all thank you for your great solutions!
I also tried my best and came up with this here.
var friendsIDs = ["id1", "id2", "id3"];
var friendsNames = ["name1", "name2", "name3"];
var friendLinks = [];
for (i=0; i < friendsIDs.length; i++){
friendLinks.push("<a href=/dashboard/" + friendsIDs[i] + " class=\'list-group item list-group-item-action\' >" + friendsNames[i] + "</a>")
}
//Create HTML Element for the Company Relations
var linkTarget = document.getElementById('linkTarget');
for(i=0; i < friendLinks.length; i++){
linkTarget.innerHTML += friendLinks[i];
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="list-group" id="linkTarget"></div>

Related

How to turn the elements in a div into an array with js/jQuery

I'm trying to make a list of buttons and their names into an array in javascript?
I heave searched the internet for help but not found anything so far. The div with the name "apps" is where I'm trying to grab from and the array inside of the if statement in the javascript code is what I'm to to replace with the array.
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="clicker.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title>Vairoon's clicker</title>
</head>
<body>
<button onclick="smnPlayer()">Get new player</button>
<p>Players per click: <span id="PPC">1</span></p>
<p>Players: <span id="players">0</span></p>
<p>New players per second: <span id="PPS">0</span></p>
<div class="upgrade">
<p>Upgrade your clicker game: <span id="upgCost">400</span></p>
<button id="upgrade">Upgrade clicker</button>
</div>
<div id="apps" name="apps"> <!-- The div I'm trying to grab from-->
<button>Obj1</button>
<button>Obj2</button>
</div>
<script ="clicker.js"></script>
</body>
</html>
Javascript code:
var players=0;
var PPS=0;
var PPC=1;
var upgradeCost=400;
var apps = ["New buildings","More upgrades","Adverts","More minigames"]
var basecosts = [0,20,100,1500,15000]
function getEl(elID) {
return document.getElementById(elID);
}
function smnPlayer() {
players+=PPC;
document.getElementById("players").innerHTML=players;
}
getEl("upgrade").onclick = function upgrade() {
if (players>=upgradeCost) {
players-=upgradeCost;
upgradeCost=upgradeCost*3;
PPC=Math.ceil(PPC*2);
PPS=PPS*2;
getEl("players").innerHTML=players;
getEl("upgCost").innerHTML=upgradeCost;
getEl("PPC").innerHTML=PPC;
getEl("PPS").innerHTML=PPS;
}
}
setInterval(() => {
if (players>=upgradeCost) {
getEl("upgrade").style.display="block";
} else {
getEl("upgrade").style.display="none";
}
for (let index = document.querySelectorAll('#apps').length; index < basecosts.length+1; index++) {
if (players>=basecosts[index]) {
if (array.includes(apps[index])){}else{ //the "array" is what to replace with the array
var button = document.createElement("BUTTON");
button.innerHTML = apps[index];
document.getElementById("apps").appendChild(button);
}
}
}
},10)
If you still don't understand what I'm trying to do, here's another explanation:
I want the code to go from
<div>
<button>Obj1</button>
<button>Obj2</button>
</div>
to
["Obj1","Obj2"]
Oh and a question if you can answer too, how do I add break line between the items I'm creating just with js?
For your simplified example:
myArray = Array.from(document.querySelectorAll("div button")).map(
function(b) {
return b.innerText;
}
);
console.log(myArray);
//add a line break:
document.querySelector("div").insertBefore(document.createElement("br"),document.querySelectorAll("div button")[1]);
<div>
<button>Obj1</button>
<button>Obj2</button>
</div>

on pressing the cancel button of a todo list item, it removes all the below to-do list items, here is the code of my to-do list

Here is my HTML and JS code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
<script src="functions.js"></script>
</body>
</html>
Here is my Javascript code
'use strict'
const buttonclick = document.getElementById('button')
const list = document.getElementById('lists')
const a = "<span><button class = 'rbutton'>X</button></span>" //list-item button
const clickhandler = () => {
const text = document.getElementById('text')
//creating a list element
if(text.value != ''){
let Newdiv = document.createElement('div')
// appending elements
Newdiv.innerHTML = text.value + a
list.appendChild(Newdiv)
let b = document.getElementsByClassName('rbutton')
if(b !=[]){
for(let i = 0; i < b.length; i++){
b[i].addEventListener('click', function(){
b[i].parentElement.parentElement.remove();
console.log(b)
})
}
}
//reseting the textarea value
text.value = ''
}
}
buttonclick.addEventListener('click', clickhandler)
An error in shown on delete a item: Cannot read property 'parentElement' of undefined at HTMLButtonElement. .
Can someone please explain what is wrong in my code and what does the error mean.
thankyou
On every click of the button you are attaching event handlers to the whole group again.
On the first iteration, 1st button has one delete handler.
On second iteration, 1st button has 2 event handler(one for buttons[0] and one for buttons[1]), and 2nd has one.
So on.
Use this. It will always point to the element to the event on which the event handler is attached:
this.parentElement.parentElement.remove();
Another way is to simply use this.parentElement.parentElement.remove()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
<script>
"use strict";
const buttonclick = document.getElementById('button');
const list = document.getElementById('lists');
const a = "<span><button class = 'rbutton'>X</button></span>"; //list-item button
const clickhandler = () => {
const text = document.getElementById('text');
//creating a list element
if(text.value != '') {
let Newdiv = document.createElement('div');
// appending elements
Newdiv.innerHTML = text.value + a;
list.appendChild(Newdiv);
let b = document.getElementsByClassName('rbutton');
for(let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function() {
this.parentElement.parentElement.remove();
});
}
//reseting the textarea value
text.value = '';
}
}
buttonclick.addEventListener('click', clickhandler);
</script>
</body>
</html>
You should use window.event.target.parentElement... to get the button instead of b[i].parentElement....
"use strict";
const buttonclick = document.getElementById('button');
const list = document.getElementById('lists');
const a = "<span><button class = 'rbutton'>X</button></span>"; //list-item button
const clickhandler = () => {
const text = document.getElementById('text');
//creating a list element
if(text.value != '') {
let Newdiv = document.createElement('div');
// appending elements
Newdiv.innerHTML = text.value + a;
list.appendChild(Newdiv);
let b = document.getElementsByClassName('rbutton');
for(let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function() {
window.event.target.parentElement.parentElement.remove();
});
}
//reseting the textarea value
text.value = '';
}
}
buttonclick.addEventListener('click', clickhandler);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
</body>
</html>

Trying to create a random word game that will output a function with a click of an html button

I'm trying to create a word game that will choose a random item from a list but some of the items have different weights so they show up less often. I want the function to be called once the user presses a HTML button. I have the code working fairly well right now (to the console). My question is how can I get the output from the function into the html web page. If anyone could help me with this, it would be a huge help.
Here's my code:
var item = {
'apple':10,
'banana':10,
'orange':10,
'grapes':1,
}
function testGame(input) {
var array = [];
for(var item in input) {
if(input.hasOwnProperty(item) ) {
for(var i=0; i<input[item]; i++ ) {
array.push(item);
}
}
}
return array[Math.floor(Math.random() * array.length)];
}
console.log(testGame(item));
I have some HTML code too, just don't know where or how to write the button code properly to produce the outcome I'm looking for.
Here's the HTML
<!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">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<script src="index.js"></script>
<button onclick="testGame();">Test</button>
</body>
</html>
You can make new function where you can call it on button just like you called it with console.log:
<button onclick="start();">Test</button>
and call your randomizing function inside:
function start() {
testGame(item)
}
Then inside function testGame don't use return, just save random word result in variable and print it in HTML:
var result = array[Math.floor(Math.random() * array.length)];
console.clear();
console.log(result);
document.getElementById("result").innerHTML=result;
I have added div result in HTML:
<div id="result"></div>
EXAMPLE SNIPPET:
var item = {
'apple': 10,
'banana': 10,
'orange': 10,
'grapes': 1,
}
function testGame(input) {
var array = [];
for (var item in input) {
if (input.hasOwnProperty(item)) {
for (var i = 0; i < input[item]; i++) {
array.push(item);
}
}
}
var result = array[Math.floor(Math.random() * array.length)];
console.clear();
console.log(result);
document.getElementById("result").innerHTML=result;
}
function start() {
testGame(item)
}
<!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">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<div id="result"></div>
<script src="index.js"></script>
<button onclick="start();">Test</button>
</body>
</html>
Use getElementById to get an element by id, for this I gave your button an id. With addEventListener you can add an event (here: click) to be call a function.
Doing here your randomizing. Get the element where you want the output again with getElementByIdand add with textContent your answer to it.
const ITEMS = {
'apple':10,
'banana':10,
'orange':10,
'grapes':1,
}
document.getElementById('btn').addEventListener('click', function testGame() {
var array = [];
for(var item in ITEMS) {
if(ITEMS.hasOwnProperty(item) ) {
for(var i=0; i<ITEMS[item]; i++ ) {
array.push(item);
}
}
}
document.getElementById('item').textContent = array[Math.floor(Math.random() * array.length)];
});
<!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">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<button id='btn'>Test</button>
<div id='item'></div>
</body>
</html>

Why does appending at 3 lines back cause it to crash?

So. This is the starting code for a javascript parser that I'm working on. What's wrong is this: It crashes any time that let is in there. So if I try to type, it just freezes the page so I have to reload. The effect only takes place after I start to type, since it's an onchange event. Can someone helps me? All helps are appreciated!
document.write('not working');
let jsAreas = document.getElementsByClassName('jsArea')
document.write('Not working')
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
let commenter = document.getElementById('commenter')
for(let i = 0; i < jsAreas.length; i++){
let jsArea = jsAreas[i]
jsArea.addEventListener('keyup', e => {
commenter.textContent = ''
let varRegex = /let/g
var b = document.getElementsByTagName('b');
while(b.length) {
var parent = b[ 0 ].parentNode;
while( b[ 0 ].firstChild ) {
parent.insertBefore( b[ 0 ].firstChild, b[ 0 ] );
}
parent.removeChild( b[ 0 ] );
}
while(varRegex.test(jsArea.innerHTML)){
commenter.textContent += varRegex.lastIndex
jsArea.innerHTML = jsArea.innerHTML.splice(varRegex.lastIndex - 3, 0, '<b>')
jsArea.innerHTML = jsArea.innerHTML.splice(varRegex.lastIndex + 3, 0, '</b>')
}
commenter.textContent += `Comment: This is the found: ${jsArea.innerHTML.match(varRegex)}. This is the other thing: ${jsArea.innerHTML}. The last index is: ${varRegex.lastIndex} `
})
}
<!-- This is a static file -->
<!-- served from your routes in server.js -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Welcome to Glitch!</title>
<meta name="description" content="A cool thing made with Glitch">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- import the webpage's stylesheet -->
<link rel="stylesheet" href="/style.css">
<!-- import the webpage's client-side javascript file -->
<script src="/client.js" defer></script>
</head>
<body>
<div class="jsArea" contenteditable="true">let=</div>
<p id='commenter'>
Comments:
</p>
<footer>
Made with Glitch!
</footer>
<!-- include the Glitch button to show what the webpage is about and
to make it easier for folks to view source and remix -->
<div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div>
<script src="https://button.glitch.me/button.js"></script>
<script src="https://rare-leek.glitch.me/client.js">
</script>
</body>
</html>

Template literals are not interpolating variables

Just noticed today that template literals with html tags don't work, or maybe I wrote it wrong?
I tried to include p tags in the template literals (which I commented out in the snippet), but it didn't work. Does anyone have any ideas? Thanks!
var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');
blueBtn.addEventListener('click', function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
addHTML(ourData)
};
ourRequest.send();
});
function addHTML(data) {
var content = '';
for (let i of data) {
console.log(i);
content += '<p>' + i.name + ' is a ' + i.species + '.</p>';
//content += '`<p>${i.name} is a ${i.species}.</p>`'; <--this one doesn't work
}
aniBox.insertAdjacentHTML('beforeend', content);
}
<!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">
<title>JSON and AJAX</title>
</head>
<body>
<header>
<h1>JSON and AJAX</h1>
<button id="btn">Fetch Info for 3 New Animals</button>
</header>
<div id="animal-info"></div>
<script src="js/main.js"></script>
</body>
</html>
Templates are needed to be enclosed in backticks. You don't need to enclose template in quotes again.
You need to change this:
'`<p>${i.name} is a ${i.species}.</p>`'
to this:
`<p>${i.name} is a ${i.species}.</p>`
The former is just a plain JavaScript string, but the latter is the template literal syntax and it allows the sections in ${ ... } to be interpolated.
See the following working example:
var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');
blueBtn.addEventListener('click', function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
addHTML(ourData)
};
ourRequest.send();
});
function addHTML(data) {
var content = '';
for (let i of data) {
console.log(i);
// content += '<p>' + i.name + ' is a ' + i.species + '.</p>';
content += `<p>${i.name} is a ${i.species}.</p>`;
}
aniBox.insertAdjacentHTML('beforeend', content);
}
<!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">
<title>JSON and AJAX</title>
</head>
<body>
<header>
<h1>JSON and AJAX</h1>
<button id="btn">Fetch Info for 3 New Animals</button>
</header>
<div id="animal-info"></div>
<script src="js/main.js"></script>
</body>
</html>
Read more about template literals in the documentation.

Categories

Resources