Problems with javascript html dom - javascript

let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
for (let i = 0; i < tasks.length; i++) {
const p = document.createElement("p");
p.innerText += tasks[i]
document.body.append(p)
console.log(tasks)
}
}
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<p id="t"></p>
</body>
</html>
Basically i have this problem when i hit my add button second time it add again the first element from the array butt how do i manage to show only the last element without the first one in the next p elements when i hit add button

If you need list of p
let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
const instance = document.getElementById("t")
instance.innerHTML = '';
for (let i = 0; i < tasks.length; i++) {
const p = document.createElement("p");
p.innerText += tasks[i];
instance.appendChild(p);
}
}

If I understand your need correctly, you do not want to "repeat" displaying "task" entered previously (which will result in displaying previous input tasks multiple times) when you perform entering new task(s).
In that case, please clear the element "t" before you update it.
So the HTML is
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="enter the task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<div id="t"></div>
</body>
</html>
and the JS (motor.js) is
let tasks = []
function addV(){
if (document.getElementById("bara").value !=""){
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
var tempstring=""
for(let i = 0;i<tasks.length;i++){
tempstring=tempstring +"<br>"+ tasks[i];
//const p = document.createElement("p");
// p.innerText += tasks[i]
// document.body.append(p)
}
document.getElementById("t").innerHTML=tempstring;
document.getElementById("bara").value="";
}
}

Your DOM p tag was inside the loop thus out of scope. I also created a new taskArray to hold the new tasks. This can be seen in the console log and the innerHTML is now displaying each new task just the one time.
let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
let taskArray = [];
const p = document.createElement("p");
for (let i = 0; i < tasks.length; i++) {
p.innerText = tasks[i]
document.body.append(p)
taskArray.push(tasks[i]);
}
console.log(taskArray);
}
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<p id="t"></p>
</body>
</html>

Related

function to return something x amount of times,specified by a parameter? [duplicate]

This question already has answers here:
Repeat a string in JavaScript a number of times
(24 answers)
Closed 1 year ago.
I have a function which returns an html element like addSpan(times),is there a way to return this element as many times as specified in the parameter items ?
vanilla js is welcomed!
function addSpan(times){
const span = `<span>This is a span</span>`
return span
}
$("body").append( addSpan(2) ) //is supposed to add 2 spans
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>
Please use Array.map() function.
function addSpan(times){
const spans = [...Array(times)].map(val => "<span>This is a span</span>").join('')
return spans
}
use yield
function* addSpan(times){
for(var i=0; i < times; i++){
const span = document.createElement('span');
span.innerText = "Some text" ;
yield span;
}
}
for (let element of addSpan(2)) {
$("body").append(element)
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>
Yes. Possible.
Like this:
function addSpan(count)
{
let result = "";
for (var i = 0; i < count; i++)
{
result += "<span>This is a span</span>";
}
return result;
}
You need loop until you reach the count and return spans.
function addSpan(times){
let spans = "";
const span = `<span>This is a span</span>`;
for (let i = 0; i < times; i++){
spans += span;
}
return spans;
}
$("body").append(addSpan(2));
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>

Why doesnt the text content of the players reset once "reset" button is clicked?

console.log(`on`)
let p1btn = document.querySelector(`#p1`);
let p2btn = document.querySelector(`#p2`);
let p1Score = document.querySelector(`#p1Score`);
let p2Score = document.querySelector(`#p2Score`);
let total = document.querySelector(`span`);
let buttons = document.querySelectorAll(`button`);
let p1Numb = parseInt(p1Score.textContent);
let p2Numb = parseInt(p2Score.textContent);
let reset = document.querySelector(`#reset`);
let winner = document.querySelector(`#hiddenWin`);
let realwin = document.querySelector(`#winner`);
reset.addEventListener(`click`,()=>{
p1Score = 0;
p2Score = 0;
console.log(total)
realwin.textContent = ``;
})
p1btn.addEventListener(`click`,()=>{
if(p1Numb<5 &&p2Numb<5){p1Numb ++;
p1Score.textContent = p1Numb;
console.log(p1Score.textContent)}
else{;
console.log(`p1 wins`);
realwin.textContent = `p1`}
})
p2btn.addEventListener(`click`,()=>{
if(p2Numb<5 &&p1Numb<5){p2Numb ++;
p2Score.textContent = p2Numb;
console.log(p2Score)}
else{realwin.textContent = `p2`}
})
<!DOCTYPE html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<body>
<p>p1 score : <span id="p1Score">0</span></p>
<div id="hiddenWin"><h1>winner is:<span id="winner"></span></h1> </div>
<p>p2 score : <span id="p2Score">0</span></p>
<button id="p1">p1</button>
<button id="p2">p2</button>
<button id="reset">reset</button>
<script src="pro.js" type="text/javascript"></script>
</body>
</html>
Hi, I've been trying to make a score keeper game, but now I've ran into a wall for 50minutes already. I've been trying to reset the numbers of both players once the reset button is clicked, but everytime I try to fix it , it just doesnt work the way I want to do, for example it stops updating the numbers of both players, or just doesnt reset at all, so any guidance is really helpful, thanks!
Instead of simply setting the values to 0. You should use textContent:
reset.addEventListener('click',() => {
p1Score.textContent = 0;
p2Score.textContent = 0;
console.log(total)
realwin.textContent = ``;
})

How to create a JavaScript loop to display an output 100 times

I’m doing an exercise for high school. The exercise is to create an input and the input needs to be displayed 100 times ( 1) input 2) input 3) input, etc..) and you are not allowed to do it manually; you need to create a loop.
This is what I have so far. I tried googling it for an hour, but I didn't find anything.
<!DOCTYPE HTML>
<html>
<head>
<title>JS example</title>
<style>
body{font-size: 130%; background-color: teal; color: yellow}
input, button {font-size: 90%;}
#output {font-weight: bold; color: blue}
</style>
<script>
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
document.getElementById(id).innerHTML = reply;
}
function reply(){
var textFromUser = getText("myTextField");
var str = something;
showReply("output", reply);
}
var something = [
[var text = "";]
[var i;]
[for (i = 0; i < 5; i++) {]
[reply += i + ")" + textFromUser;}]
]
</script>
</head>
<body>
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <span id="output"></span> </p>
</body>
</html>
How can I do it?
You can create an element and append to your output container using a for loop. Try this:
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
let container = document.getElementById(id);
let p = document.createElement('p');
p.textContent = reply;
container.appendChild(p);
}
function reply(){
var textFromUser = getText("myTextField");
for(let i = 0; i < 100; i++){
showReply("output", textFromUser);
}
}
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <div id="output"></div> </p>
Variable i is used as a counter. If you want to change how many times it loops, just change the i<=num.
for (var i=1; i<=100; i++){
show_reply();
}
I suggest you to check this post on W3Schools.
I've made two files, one for HTML and the other for JavaScript.
Here is the JavaScript code:
function getText(id) {
let text = document.getElementById(id).value;
return text;
}
function showReply(id, reply) {
document.getElementById(id).innerHTML = reply;
}
function reply() {
let textFromUser = getText("myTextField");
let i;
let span1 = document.getElementById("output")
let usert = ""
for (i = 0; i < 100; i++) {
usert += "<br>" + textFromUser
}
span1.innerHTML = usert
}
Here is the HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>JS example</title>
<style>
body{font-size: 130%; background-color: teal; color: yellow}
input, button {font-size: 90%;}
#output {font-weight: bold; color: blue}
</style>
<script src="main.js"></script>
</head>
<body>
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <span id="output">dd</span> </p>
</body>
</html>
There are many different potential solutions for this type of question. Choose the flavor you like and put your own spin on it.
function showReply(id, reply){
document.getElementById(id).innerHTML = reply.join('<br>');
}
function reply(){
var textFromUser = getText('myTextField');
var outputs = [];
for (let i = 0; i < 100; i++){
outputs.push(`#${ i } ${ textFromUser }`)
}
showReply('output', outputs);
}

how to initialize a member of JS array?

I just wrote this in order to take n from user and also n names , and then print them on screen after clicking on button , but i cant initialize my array ...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
var n;
var i =0;
var names = [];
function mf1(){
n=parseInt(document.getElementById("n").value);
}
function mf2(){
if (i<n){
names[i]=document.getElementById("nam").value;
i++;
document.getElementById("rem").innerHTML=names[i];
}
}
</script>
inset n : <input type="text" id="n"> <button onClick="mf1()">take n</button>
insert name: <input type="text" id="nam"> <button onClick="mf2()"> take name</button>
<p id="rem"></p>
</body>
</html>
The problem is that in function mf2 you can't access names[i] because you increment i++ before.
var n;
var i = 0;
var names = [];
var input1 = document.getElementById("n");
var input2 = document.getElementById("nam");
function mf1(){
n = parseInt(input1.value);
console.log(n);
}
function mf2(){
if (i < n){
names[i] = input2.value;
console.log(names);
document.getElementById("rem").textContent = names[i];
i++;
}
}

Why does content of h1 tag doesnot change after clicking reset button?

var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1").innerHTML = "<h1>0 to 0</h1>";
});
// it doent work when i add textcontent in place of inner html
> why does content of h1 doesnot change when i click reset button.
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
<script type="text/javascript" src="score.js"></script>
</html>
why does content of h1 doesnot change when i click reset button.
Problem :
document.getElementsByTagName returns an array so you will need index you could use
document.getElementsByTagName("h1")[0].innerHTML = "<h1>0 to 0</h1>";
But a better version is this :
var one = document.getElementById("one"),
two = document.getElementById("two"),
reset = document.getElementById("reset"),
i = 0,
j = 0;
one.addEventListener("click", function() {
i ++;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j ++;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
i = 0 , j = 0
document.getElementById("resetId").innerHTML = "<span id="d1">0</span> to <span id="d2">0</span>"; // Thanks to #Micheale
});
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1 id='resetId'><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
<script type="text/javascript" src="score.js"></script>
</body>
</html>
You are using getElementsByTagName which doesn't return a single element like getElementById. It returns an HTMLCollection/NodeList (depending on which browser), but you can just treat it like a standard array.
You should select the first element by using getElementsByTagName[0] instead.
You can either use innerHTML or textContent, but they do different things.
innerHTML would replace the contents of the h1 tag with whatever you assign. So, document.getElementsByTagName("h1").innerHTML = "<h1>0 to 0</h1>"; would output two h1 elements, which you don't want.
So in either case, set innerHTML or textContent to simply 0 to 0
var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1")[0].innerHTML = "0 to 0";
});
// it doent work when i add textcontent in place of inner html
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
</html>
document.getElementsByTagName("h1") returns an array so you have to select the h1 you want.
Your code modified to take first h1 (assuming it is always the good one).
var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1")[0].innerHTML = "<h1>0 to 0</h1>";
});
// it doent work when i add textcontent in place of inner html
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
<script type="text/javascript" src="score.js"></script>
</html>
Three problems here:
1- getElementsByTagName returns an array, not an element. You can retrieve the first element of the array with "[0]" as I've done in the snippet.
(I'd recommend giving that header an id.)
2- Problems with the innerHTML for h1. When replacing the h1 innerHTML, there's no need to repeat the h1 tags (you end up with nested h1s). But another problem is that you shouldn't forget the d1 and d2 spans, otherwise the code breaks.
3- Also, don't forget to reset i and j
var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1")[0].innerHTML = '<span id="d1">0</span> to <span id="d2">0</span>';
i = j = 0;
});
// it doent work when i add textcontent in place of inner html
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
<script type="text/javascript" src="score.js"></script>
</html>
EDIT: I see some other people have got here first, but I'll leave my answer up for now because the other answers don't maintain the spans with id d1 and d2, which makes the code fail after hitting reset

Categories