Display javascript array in div - javascript

I am trying to make a basic to do application.
Here is what I have done so far;
When the user clicks a button a prompt appears asking the user to enter a task.
The task will then be stored in an array
I have displayed the array in the console. However, I am having trouble displaying the array on the web page:
var toDoItems = [];
var parsed = "";
document.getElementById("addItem").onclick = function() {
var userInput = prompt("Enter your Todo: ")
toDoItems.push = userInput;
console.log(toDoItems);
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>To Do List</title>
</head>
<body>
<h1>My Tasks</h1>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
<script src="js/script.js"></script>
</body>
</html>

The first thing is you need to use Array.push() and not Array.push = someVal. Then you can loop over to the values and create a list of elements in the HTML:
var toDoItems = [];
var parsed = "";
document.getElementById("addItem").onclick = function() {
var nHTML = '';
var userInput = prompt("Enter your Todo: ")
toDoItems.push(userInput);
toDoItems.forEach(function(item) {
nHTML += '<li>' + item + '</li>';
});
document.getElementById("item-list").innerHTML = '<ul>' + nHTML + '</ul>'
}
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>To Do List</title>
</head>
<body>
<h1>My Tasks</h1>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
<script src="js/script.js"></script>
</body>

You can use map() to map over the toDoItems and convert each items to html code and then use join() to combine the array into one string of HTML code.
Like this:
const HTML = toDoItems.map( item => `<li>${item}</li> ` ).join('');
document.getElementById("item-list").innerHTML = '<ul>' + HTML + '</ul>'
Edit: Fixed typo (should be join, not joint)

Loop over toDoItems, create a <p> tag and append it to #item-list:
toDoItems.forEach((item) => {
let p = document.createElement('p');
p.innerText = item;
document.querySelector('#item-list').appendChild(p);
});

You can use innerHTML for this
document.getElementById("item-list").innerHTML += "<p>" +userInput+"</p>";
demo : plunker

Check below I think this may help you
I removed style from your code for my convenience
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>To Do List</title>
<script>
function myFunction(){
var toDoItems = [];
var parsed ="";
var userInput = prompt("Enter your Todo: ")
toDoItems.push = userInput;
document.getElementById("item-list").innerHTML=userInput;
console.log(toDoItems);
}
</script>
</head>
<body>
<h1>My Tasks</h1>
<button id="addItem" onclick="myFunction()">Add item</button>
<div id="item-list">
</div>
</body>
</html>

The Code above has an drawback: It erases the old value of userInput when you enter a new value in prompt().
I propose:
document.getElementById("item-list").innerHTML +=userInput+"";
Vu

Related

How to send the data by using click method to another html file while executing the function?

I want to send content of section tag from First file to second file using jQuery method and function which execution is inside of that method, the definition of that function is in seperate file as it shown below. I got Uncaught TypeError: Cannot read property 'push' of null - I don't know where is my mistake.
first HTML
cart = [];
class Item {
constructor(name, price, count){
this.name = name;
this.price = price;
this.count = count;
};
}
addItemToCart = function(name,price,count){
for (let i in cart) {
if ((cart[i]).name === name){
(cart[i]).count += count;
return;
}
}
let item = new Item(name,price,count);
(cart).push(item);
$("#show-cart").html(cart)
}
saveCart = function(){
localStorage.setItem("cart",JSON.stringify(cart));
}
loadCart = function(){
cart = JSON.parse(localStorage.getItem("cart"));
}
loadCart();
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="shopcart.css">
</head>
<body>
<section class="a" id="title">Relax in the morning</section>
<section class="a" id="price">100$</section>
<form id="form1" runat="server">
<div>
<input type="button" id="btnClick" value="Submit" onclick="addItemToCart(title,price,1);" />
</div>
</form>
<script>
$("section").click(function(event){
event.preventDefault();
const name = $(this).attr("#title");
const price = Number($(this).attr("#price"));
localStorage.setItem("title",JSON.stringify(name));
localStorage.setItem("price", JSON.stringify(price));
addItemToCart(name,price,1);
});
</script>
<script src="main.js"></script>
</body>
</html>
<html>
<head>
<title> Shopping Cart</title>
<link rel="stylesheet" href="shopcart.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<main>
<div id="show-cart"></div>
</main>
<footer>
</footer>
<script src="main.js">
const title = JSON.parse(localStorage.getItem("title"));
const price = JSON.parse(localStorage.getItem("price"));
</script>
</body>
</html>

'Li' element showing as `undefined`

Started to do a todo list on my own to practice JS
When I add the text/task to the todo, HTML text showing-
Undefined
Made sure getElementbyId etc was right but unsure if missing something. Design is rubbish, just want to try JS out.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>To doist</title>
</head>
<body>
<div class= "main-title-bar">
<h1>To doist</h1>
</div>
<div id = "button">
<button>+</button>
</div>
<div class = "input" id = "input">
<input type="text" class="add_tast" placeholder="Task">
<span onclick="newElement()" onkeypress="newElement()" class="addBtn">Add</span>
</div>
<div class = "todo-list">
<ul id="myUL">
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>
JAVASCRIPT
//Click button to get input field
let button = document.getElementById('button')
button.addEventListener("click",showInput)
function showInput(event){
if(event.type === "click"){
input.classList.toggle("show")
}
}
const input = document.querySelector(".input")
// Create new element for the classList
function newElement(){
let li = document.createElement("li");
let inputValue = document.getElementById("input").value;
let t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === ''){
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("input").value = "";
console.log('Is it working?');
}
Expecting to see the name of my task on HTML as for example "Going to the gym"
You have given the id="input" to the div instead of the input element. Give the id to the input an it will work
let button = document.getElementById('button')
button.addEventListener("click",showInput)
function showInput(event){
if(event.type === "click"){
input.classList.toggle("show")
}
}
const input = document.querySelector(".input")
function newElement(){
let li = document.createElement("li");
let inputValue = document.getElementById("input").value;
let t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === ''){
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("input").value = "";
console.log('Is it working?');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>To doist</title>
</head>
<body>
<div class= "main-title-bar">
<h1>To doist</h1>
</div>
<div id = "button">
<button>+</button>
</div>
<div class = "input" >
<input type="text" id = "input" class="add_tast" placeholder="Task">
<span onclick="newElement()" onkeypress="newElement()" class="addBtn">Add</span>
</div>
<div class = "todo-list">
<ul id="myUL">
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>
I have fixed your code. document.getElementById("input").value;
input tag is not id it's tag.
if you want get value from input tag must using through id use to this code.
document.getElementById("id").value;
let button = document.getElementById('button')
button.addEventListener("click",showInput)
function showInput(event){
if(event.type === "click"){
input.classList.toggle("show")
}
}
const input = document.querySelector(".input")
// Create new element for the ClassList
function newElement(){
debugger;
let li = document.createElement("li");
let inputValue = $("#tasks").val();
let t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === ""){
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("input").value = "";
console.log('Is it working?');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>To doist</title>
</head>
<body>
<div class= "main-title-bar">
<h1>To doist</h1>
</div>
<div id = "button">
<button>+</button>
</div>
<div class = "input" id = "input">
<input type="text" id="tasks" class="add_tast" placeholder="Task">
<span onclick="newElement()" onkeypress="newElement()" class="addBtn">Add</span>
</div>
<div class = "todo-list">
<ul id="myUL">
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>

Count key presses and display them in HTML

I made a simple "spacebar simulator" game with HTML and JavaScript. Every time the user presses spacebar an image is replaced with another one, and when the key is released it is reset to the original image.
I would like to add a counter to the page, which counts the number of times the user has pressed spacebar. The source code is below:
var myRealUrl = "./assets/spacebar.png";
$("body").on("keydown", function (e) {
if(e.which == 32){
$("#spacebar").attr("src", "./assets/spacebar_pressed.png")
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
var button = document.getElementById('counter'),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
<span id="counter"><p></p></span>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed</p><p id="counter">0</p><p> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>
So set up a page level variable and increment it in the keydown event handler.
Your attempt at the "button" click code didn't work because the p element that needed to be clicked had no content inside of it, so it wasn't rendering on the screen and therefore there was nothing to click on.
Also, you can't have more than one element with the same id and it's invalid to put a p inside of a span.
var counter = 0; // Variable to hold the count
var myRealUrl = "./assets/spacebar.png";
var count = document.getElementById('counter');
$("body").on("keydown", function (e) {
if(e.which == 32){
counter++; // Increment the counter
$("#spacebar").attr("src", "./assets/spacebar_pressed.png");
count.textContent = counter; // Log the count
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed <span id="counter">0</span> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>

How do I output a variable from Javascript to html?

I want to inject text into a div using a variable. Here's a Stack Snippet of my code:
tDNA() {
var dna = prompt("Enter the DNA: ");
}
document.getElementById("dna").innerHTML = "DNA: " + dna;
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<src="main.js">
<div id="dna"></div>
</body>
</html>
function promp
You need to import your script like this
<script type="text/javascript" src="main.js"></script>
You can try this out.
HTML
<html>
<head>
</head>
<body>
<script defer src = "main.js"></script>
<div id = "dna">
<p></p>
</div>
</body>
</html>
JavaScript
function promptDNA(){
var dna = prompt("Enter the DNA: ");
d1 = document.querySelector("p");
d1.textContent = dna;
}
promptDNA();
Like this, you have to add the data to the HTML where the variable dna is in scope and then actually call the function
function promptDNA(){
var dna = prompt("Enter the DNA: ");
document.getElementById("dna").textContent = "DNA: " + dna;
}
promptDNA()
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="dna"></div>
<script src="main.js"></script>
</body>
</html>
Also, you're importing your script improperly.

Need help for a getInput function

I've been having trouble with my javascript code.
<!DOCTYPE html>
<html>
<head>
<title>js-game</title>
<script src="script.js" type="text/javascript"></script>
<script src="story.js" type="text/javascript"></script>
<link href="style.css" rel="stylesheet" type="text/css"/>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="game">
<ul id="output">
<li onclick="main()">Click here to start!</li>
</ul>
<input autofocus id="inputLine" type="text">
<p onclick="" id="enterInput">ENTER</p>
</div>
</body>
</html>
// Variables
var log="<li>Hello</li>";
var lastVar="";
// Functions
function getInput() {
document.getElementById("enterInput").addEventListener("click", function() {
return document.getElementById("inputLine").value;
document.getElementById("inputline").value="";
});
}
function output(output) {
log=log + "<li>" + output + "</li>";
document.getElementById("output").innerHTML=log;
}
function main() {
output("What's your name?");
alert(getInput());
}
As you can probably see I want to get input from a <input type="text"> with the id of inputLine. And a button with the id of enterInput.
But all I get back is undefined, and I've been working on this for a long time, so I'm getting frustrated.
Sorry for bad english.
Try doing it like so:
document.getElementById("enterInput").addEventListener("click", getInput );
function getInput() {
var val = document.getElementById("inputLine").value;
//do something with val
document.getElementById("inputLine").value="";
return val;
}
See this demo
Or to fetch it as a variable with getInput():
document.getElementById("enterInput").addEventListener("click", function(event){
var val = getInput();
alert(val);
});
function getInput() {
var val = document.getElementById("inputLine").value;
document.getElementById("inputLine").value="";
return val;
}
See this demo

Categories