I am getting a new array element from an input and adding to array but I can not print every element in a new row. I can print all elements of array in one row but can not print every element in a different row. I am using <br> after array name but does not work. What is your solution? It is like a todo list project.
var allmembers = [""];
function addnewmember() {
var newmemberr = document.getElementById("newmember").value;
allmembers.push(newmemberr);
for (var i = 0; i < allmembers.length; i++) {
document.getElementById("membername").innerHTML = allmembers[i] + "<br>";
}
}
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stil.css">
</head>
<body>
<input id="newmember" placeholder="NEW MEMBER"><br>
<button type="button" onclick="addnewmember()">SEND</button>
<div id="members">MEMBERS</div>
<div id="membername"></div>
</body>
</html>
Your solution is appending a <br> to the end of the array, rather than between array items. Instead of looping over the array, just use the .join() method, which is ideal for something like this.
Additionally, using innerHTML in a loop is a big performance "no no" as it causes the browser to have to repaint and possibly reflow the DOM document repeatedly. In such cases, you should build up a string that contains the HTML you want and after the loop is done set that string as the innerHTML of the desired element in one single command. And really, the use of innerHTML should be avoided if at all possible because of security concerns as well.
See additional comments inline:
let allmembers = [];
// Get your DOM references just once, not every time the function runs
// Make references to DOM elements, rather than their propreties. This
// way, if you decide you need access to a different DOM element property
// you don't have to scan for the element again.
let newmember = document.getElementById("newmember");
let memberName = document.getElementById("membername");
function addnewmember() {
allmembers.push(newmember.value);
newmember.value = ""; // Clear out the input
// No need for a loop. Just join the arry elements
// with a <br> between them.
memberName.innerHTML = allmembers.join("<br>");
}
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stil.css">
</head>
<body>
<input id="newmember" placeholder="NEW MEMBER"><br>
<button type="button" onclick="addnewmember()">SEND</button>
<div id="members">MEMBERS</div>
<div id="membername"></div>
</body>
</html>
Related
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I´m trying to make a simple To-do List, and I want it to have a button to add the tasks that I want and another button to remove all tasks but when I click the delete button I get an error: "Cannot read property 'removeChild' of undefined" I don´t know why it says the parentNode is undefined.
Here is the 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" href="style.css">
<title>To do List</title>
</head>
<body>
<header>
<h1>To-do List</h1>
<div id="form">
<input type="text" name="" id="tarefa" value="Add an item!">
<button id="submit">Submit</button>
<button id="delete">Clear List</button>
</div>
</header>
<main>
<ul id="lista">
<li id="112">Test1</li>
<li>Test2</li>
</ul>
</main>
<script src="javascript.js"></script>
</body>
</html>
//Javascript file
const tarefa = document.getElementById("tarefa")
const adicionar = document.getElementById("submit")
const limpar = document.getElementById("delete")
const padre = document.getElementById("lista")
const fpp = document.querySelectorAll("li")
//Add the tasks
function enviar(e){
var coisa = document.createElement("li")
let escrito = tarefa.value;
padre.appendChild(coisa)
coisa.innerHTML = escrito
}
//Delete the tasks
function apagar(e){
fpp.parentNode.removeChild(fpp)
console.log("aaaa")
}
adicionar.addEventListener("click",enviar)
limpar.addEventListener("click",apagar)
.querySelectorAll returns a NodeList (because you're selecting all li tags, not just one), so you need to do a forEach loop. Give the context, I asume fds is supposed to be fpp (you never define fds in the code you provided), so here is the code you would need, given that assumption:
function apagar(e){
fpp.forEach(function(el) {
el.parentNode.removeChild(el)
})
}
Update
Use this so that you dont get null errors once the list is deleted the first time.
function apagar(e){
document.querySelectorAll("li").forEach(function(el) {
el.parentNode.removeChild(el)
})
}
How about
function apagar(){
padre.innerHTML = "";
}
Aim : to click box(x) and it opens pop-up(x);
This is my first javascript project, i've done loads of research but i'm still struggling.
The reason I'm using a getElementByClassList is because it returns an array. I would then take the array and get the corresponding pop-up box and change its display settings in css.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box1 boxes"></div>
<div>
<div class="box2 boxes"></div>
<div class="box3 boxes"></div>
</div>
<div class="popup1"></div>
<div class="popup2"></div>
<div class="popup3"></div>
<script>
const boxes = document.getElementsByClassName('boxes');
// i would like to add an eventlistener for each object in the array
//
</script>
</body>
</html>
document.addEventListener("DOMContentLoaded", () => { // wait till all the DOM is Loaded, since querying objects at this point they are not there yet.
const boxes = document.querySelectorAll(".boxes"); // or use getElementsBy...
boxes.forEach(box => { // we are adding a click event listener to each box
box.addEventListener('click', (e) => {
const boxNumber = e.target.className.match(/box(\d)/)[1]; // through a regex we get the box number of the className
const popup = document.querySelector(`.popup${boxNumber}`);
console.log(popup)
// do whatever you want with the popup, add a className or whatever to open it :)
});
});
});
.boxes {
height: 20px;
width: 50px;
background: red;
margin: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box1 boxes"></div>
<div>
<div class="box2 boxes"></div>
<div class="box3 boxes"></div>
</div>
<div class="popup1"></div>
<div class="popup2"></div>
<div class="popup3"></div>
<script>
const boxes = document.getElementsByClassName('boxes');
// i would like to add an eventlistener for each object in the array
//
</script>
</body>
</html>
The method getElementsByClassName() indicats that return an array of html objects, in case there exists elements with passed css class.
The first step you have to iterate trough the array object:
for (int index = 0; index < boxes.length; index++)
{
}
Within for loop access to each element and assign the eventent handle
boxes[index].addEventListnener('click', function()
{
});
Within the body of declared anonymous function add your code.
You can try :
const boxes = document.getElementsByClassName('boxes');
const popups = document.querySelectorAll(".popups");
boxes.forEach((box,index)=>box.addEventListener("click",()=>{
const popup = popups[index]; // This gets the popup based on the box index so you will have to setup the html so that the popup for box1 is the first then popup for box2 second etc.
// Add styles to popup to display it
// Example
popup.style.opacity = "1";
})
Visit the 'mdn docs' or 'youtube' to learn how the array methods like forEach work
Ok, this might be quite hard for me to explain, but I will give it a go. I have two HTML pages: form.html & display.html. The form page has an input which obtains a value and then puts it into local storage once the form is submitted. After the form submission, the user will be taken to the display page, which will then retrieve the input value from the previous page from local storage and then displays the value inside the input field on the display page. The display page will later act as a job page which will display a list of jobs which is filterable by the value inside the input field on the same page. I can get the filter function to work by using onkeyup on the input field, but I what I can't make work is the filter function with the input value from the previous page by using something like onload. The reason why I am using two pages is that I will later use this code on a website which will have a search box on the landing page, and then will be directed to the Jobs page with filtered results. I am sorry if this was really hard to understand, I will post the code below so you might better understand.
Many thanks to anyone who takes time out of their day to help me with this problem, it is much appreciated.
form.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>Document</title>
<script>
function passValues() {
var firstName = document.getElementById("txt").value;
localStorage.setItem("textValue", firstName);
return false;
}
</script>
</head>
<body>
<form action="display.html">
<input type="text" id="txt" />
<input type="submit" value="Click" onclick="passValues();" />
</form>
</body>
</html>
display.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>Document</title>
</head>
<body>
<h1>Tokyo Expat Job Search</h1>
<input onload="filter()" onkeyup="filter()" id="result" type="text">
<ul id="Menu">
<li>English Techer</li>
<li>Waiter/Waitress</li>
<li>Developer</li>
<li>Banker</li>
<li>Designer</li>
<li>Logistics</li>
</ul>
<script>
function filter() {
var filterValue, input, ul, li, a, i;
input = document.getElementById("result");
filterValue = input.value.toUpperCase();
ul = document.getElementById("Menu");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filterValue) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
document.getElementById("result").value = localStorage.getItem("textValue");
</script>
</body>
</html>
Try to add the listener to window.onload? The input does not have such an event.
window.addEventListener('load', filter, false)
Here's my problem:
I am new to Javascript and I am trying to make my image change on click.
It's a simple counter game that does a 2 frame animation of squidward hitting the dab.
So far I have got the counter to work but I cannot get the image to change on click as well. Also, it's going to have to change back to the original image so that it can be clicked and counted again.
<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">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<div class="container">
<button onclick="dabMan()"><img src="./squid-dab1.gif"> .
</button>
<br><br>
How many dabs??
<input type="text" id="text">
</div>
<script src="./script.js"></script>
</body>
</html>
var dabcount = 0;
function dabMan() {
dabcount = dabcount + 1
document.getElementById('text').value = dabcount;
console.log("dabMan", dabMan)
document.getElementById("./squid-dab1.gif") .src = "./squid-dab2.gif";
console.log("changeimage", dabMan)
}
instead of using the "onclick(){}" attribute in your html, write an event listener in js. Assuming your image tag is like this:
<img src='./squid-dab1.gif' id='myImage'>
Note: Javascript needs to know how to find your image... Hence the ID
Your javascript code should look like this:
<script>
var image = document.getElementById('myImage');
image.addEventListener('click', function(){
changeImage();
});
function changeImage(){
image.src = './squid-dab2.gif';
}
</script>
That will make it so that when you click the image, it will change. If you wanted a button to do that, simply create a button with the id "myImage" instead like so:
<button id='myImage'>Click me to change the picture</button>
I have a problem with simple thing.
I want to add a element into html div tag using createElement Method. I have tried a lot of diferent ways but always getting the same result - nothing happens.
This is my code:
function changeReleaseDate()
{
var parentElement = document.getElementByClassName("container body-content");
var existingElement = document.getElementByClassName("btn btn-default");
var newInput = document.createElement("input");
newInput.type = "text";
newInput.className = "form-control";
parentElement.insertBefore(newInput, existingElement);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class="container body-content">
<h2>Index</h2>
<button id="btn" type="button" onclick="changeReleaseDate()" class="btn btn-default">Default</button>
<hr />
<footer>
<p>©My ASP.NET Application</p>
</footer>
</div>
</body>
</html>
I also tried to use appendChild but in this case input field was placed out of div.
The problem is that getElementByClassName should be getElementsByClassName.
This method returns a HTMLCollection, so to access the first element from this list you need to use bracket with index 0:
var parentElement = document.getElementsByClassName("container body-content")[0];
var existingElement = document.getElementsByClassName("btn btn-default")[0];
Demo: http://jsfiddle.net/jak4efau/
However it's more convenient in your case to use querySelector method:
var parentElement = document.querySelector(".container body-content");
var existingElement = document.querySelector(".btn.btn-default");
Also note, that you need to take care of the case when user clicks button multiple times, you probably don't want to append multiple input fields.