Using for loop for delete button - javascript

Good evening guys. I am learning javascript. After learning some basics, I decided to make TODO LIST and got the todo list code from the internet. But I have a question on my mind. My code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div>
<h2>ToDo</h2>
<input type="text" id="inputum" />
<button onclick="fonksiyonum()">Ekle</button>
</div>
<ul id="yeniUl"></ul>
<script>
function fonksiyonum() {
var liEkle = document.createElement('li');
var inputtaYazanlar = document.getElementById('inputum').value;
var textim = document.createTextNode(inputtaYazanlar);
liEkle.appendChild(textim);
document.getElementById('yeniUl').appendChild(liEkle);
document.getElementById('inputum').value = '';
var button = document.createElement('BUTTON');
var hiks = document.createTextNode('\u00D7');
button.appendChild(hiks);
liEkle.appendChild(button);
button.className = 'close';
var close = document.getElementsByClassName('close');
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = 'none';
};
}
}
</script>
</body>
</html>
As I understand it, for (i = 0; i < close.length; i++) is used to get the button.close[i].onclick = function () shows the function that will run when the button is pressed. But why close[i] what does the letter 'i' mean here? After that there is var div = this.parentElement. I don't understand this.parentElement. I would be happy if someone could explain the concept of parent element to me.

close.length is actually List/Array of all the Buttons. You can tell by the Elements in getElementsByClassName.
So you are looping through all the Close Buttons and adding an onclick() method to each.
list = [btn0, btn1]
list.length // length = 2
// for i=0; i<list.length; i++
// 1st pass, i == 0:
list[0] // btn0
// 2st pass, i == 1:
list[1] // btn1
// 3rd pass, i == 2
// i is not less than length, 2, end.
For the parentElement I always look at the tabs, Just go 1 left tab over and up; that's the parent! That's why formatting is important, to make this easy!
<div> <!-- <- Parent -->
<h2>ToDo</h2>
<input type="text" id="inputum" />
<button onclick="fonksiyonum()">Ekle</button> <!-- <- Button --->
</div>

Related

Check for certain words in all paragraphs and add to list

I'm trying to check paragraphs to see if it contains a certain word (Apple), and if so, add that to a list.
<p>Orange</p>
<p>Grape</p>
<p>Apple</p>
<ul id=ulist>
</ul>
<script>
var i;
var x = document.getElementsByTagName("P");
for (i = 0; i < x.length; i++) {
document.getElementById("ulist").innerHTML = "<li>" + x[i].innerHTML + "<li>";
}
</script>
I'm unsure how to check for words, but first I'm trying to go through each paragraph and add each word to the list, but it's only adding Apple. I don't understand why even though I set i=0.
Expected output:
- Apple
New to Javascript so I'd appreciate if the solution uses simple code even if it's long.
Try this code:
var paragraphs = [...document.getElementsByTagName("P")];
var list = document.getElementById("ulist")
paragraphs.forEach(el => {
if (el.innerText.toLowerCase().includes("apple")) {
var li = document.createElement("LI")
li.innerText = el.innerText
list.appendChild(li)
}
})
<p>Orange</p>
<p>Grape</p>
<p>Apple</p>
<p>Not Apple</p>
<ul id="ulist"></ul>
It checks if each <p> has the word apple in it, and if so, it dynamically adds it to the list.
If you want to check if it's Apple just by itself, use ==, and if you want to make the search case-sensitive, remove the .toLowerCase() and change the word apple to Apple.
If you want to add every element, simply remove the if condition.
You should use += instead of =. Also forgot to close the list element (should be </li>). Also, for better performance you can first generate string for all the items the update the DOM only once.
You can check the text of the current element in each iteration based on which you can create items.
Demo:
<p>Orange</p>
<p>Grape</p>
<p>Apple</p>
<ul id=ulist>
</ul>
<script>
var i;
var x = document.getElementsByTagName("p");
var elString = "";
for (i = 0; i < x.length; i++) {
if(x[i].textContent.toLowerCase().includes('apple')){ // check if text contains the word
elString += "<li>"+x[i].textContent+"</li>";
}
}
document.getElementById("ulist").innerHTML = elString;
</script>
Using Document.querySelectorAll(), NodeList.prototype.forEach(),Document.getElementById(),
,Document.createElement() and RegExp.prototype.test().
const fruits = document.querySelectorAll("p"),
lists = document.getElementById("ulist");
fruits.forEach((fruit) => {
if (/apple/i.test(fruit.textContent)) {
const list = document.createElement("li");
list.textContent = fruit.textContent;
lists.append(list);
}
});
<!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>Fruits</title>
</head>
<body>
<p>Orange</p>
<p>Grape</p>
<p>Apple</p>
<ul id="ulist"></ul>
</body>
</html>

Can't figure out why it isn't working, anymore

So been trying to learn more javascript, by doing small projects that are simple but are starting stuff. One of the projects is a to-do app which for some people is really simple, but for me as a starter it's quite complex.
Now here is the thing, I had it working for the most part, I can add stuff, and one thing only HALF works, I wrote a bit that adds a X button to a li element. Now it works when I put the li element in the HTML page itself, but when it's added through javascript, it doesn't.
There is no error, it was working before but for some reason it.. broke.
<!DOCTYPE html>
<head>
<title>To Do App!</title>
<link rel="stylesheet" type="text/css" href="CSS/stylesheet.css">
</head>
<body>
<div id="h1Div">
<h1> To-do app! </h1>
<input type="text" id="inputForList">
<input type="button" id="btnInput" value="Add me!" onclick="btnFunction()">
</div>
<ul id="ulSection">
<li>Test 1</li>
<li>Test 2</li>
</ul>
<script src="Scripts/javascript.js"></script>
</body>
This is the HTML page, super simple.
//Adds li element with input from a textbox
function btnFunction(){
var cLi = document.createElement("li");
var inpList = document.getElementById("inputForList").value;
var txtNode = document.createTextNode(inpList);
cLi.appendChild(txtNode);
//Check to see if anything is filled in, otherwise send message. And 'appends' it to the list item
if(inpList === ''){
alert("Voeg wat toe!");
} else {
document.getElementById("ulSection").appendChild(cLi);
}
// Reset value of Textbox to ""
document.getElementById("inputForList").value = "";
}
//Sets a 'x' on every element.
var ulList = document.getElementsByTagName("li");
var i;
for(i = 0; i < ulList.length; i++){
var span = document.createElement("span");
var xBtn = document.createTextNode("\u00D7");
span.className = "Done";
span.appendChild(xBtn);
ulList[i].appendChild(span);
}
And this is the Javascript.
As stated, it worked before. But for some reason, now the bottom section, the X button (\u00D7) part, it sn't working on the 'new stuff' that I add through the text input..
Your code is good, you just need to do the same thing you did in
var ulList = document.getElementsByTagName("li");
var i;
for (i = 0; i < ulList.length; i++) {
var span = document.createElement("span");
var xBtn = document.createTextNode("\u00D7");
span.className = "Done";
span.appendChild(xBtn);
ulList[i].appendChild(span);
}
in btnFunction() (with the exception of the for loop, which isn't needed in the function, as only one element is added at a time). The reason for this is your code only runs when the page is loaded, or when it is specifically told to run (in your case, on a button click). if you just create an element the js doesn't know to update it with an x, you have to tell it to do so.
//Adds li element with input from a textbox
function btnFunction() {
var cLi = document.createElement("li");
var inpList = document.getElementById("inputForList").value;
var txtNode = document.createTextNode(inpList);
cLi.appendChild(txtNode);
//Check to see if anything is filled in, otherwise send message. And 'appends' it to the list item
if (inpList === '') {
alert("Voeg wat toe!");
} else {
document.getElementById("ulSection").appendChild(cLi);
var ulList = document.getElementsByTagName("li");
var span = document.createElement("span");
var xBtn = document.createTextNode("\u00D7");
span.className = "Done";
span.appendChild(xBtn);
ulList[ulList.length-1].appendChild(span);
}
// Reset value of Textbox to ""
document.getElementById("inputForList").value = "";
}
//Sets a 'x' on every element.
var ulList = document.getElementsByTagName("li");
var i;
for (i = 0; i < ulList.length; i++) {
var span = document.createElement("span");
var xBtn = document.createTextNode("\u00D7");
span.className = "Done";
span.appendChild(xBtn);
ulList[i].appendChild(span);
}
<!DOCTYPE html>
<head>
<title>To Do App!</title>
<link rel="stylesheet" type="text/css" href="CSS/stylesheet.css">
</head>
<body>
<div id="h1Div">
<h1> To-do app! </h1>
<input type="text" id="inputForList">
<input type="button" id="btnInput" value="Add me!" onclick="btnFunction()">
</div>
<ul id="ulSection">
<li>Test 1</li>
<li>Test 2</li>
</ul>
<script src="Scripts/javascript.js"></script>
</body>

Why my HTML and JavaScript button are not working together?

Hey I am new to coding and I'm working on a new chrome App. So far, I am trying to make a button that counts when you click on it. For some reason it's not working. Here's the HTML:
var button = document.getElementById("button"),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Button: " + count;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> This is a "Button" (I think) </h1>
<p> (Or is it?) </p>
<button id="button"> Button: 0 </button>
</body>
</html>
You have to wait until the DOM is loaded. Use the window.onload event:
window.onload = function() {
var count = 0;
const button = document.getElementById('button');
button.onclick = function() {
count += 1;
button.innerHTML = "Button: " + count;
};
};
Edit: I also just noticed you're not including your script in your HTML.
Your missing a variable type on your count.
You want make sure your button has some kind of text inside of it before you actually
start incrementing it.
Lastly you need to get the element from the html with a "document.getElementById("id_goes_in_here")
Try this instead.
document.getElementById("button").innerHTML = ` `; //Make sure to actually pull from your element in the html with this.
let count = 0;
button.innerHTML="Button " + count
button.onclick = function() {
count += 1;
button.innerHTML = "Button: " + count;
};

JavaScript function doesn't recognize my HTML element

I have a problem with my JavaScript function, in the "for" part it doesn't recognize the HTML elements when I use i to refer to the list position, but when I use [0] or [1], for example, it does recognize it. So there must be a problem with the loop part but I can't figure out what is it, here is the code:
(function () {
"use strict";
window.animacion_click_menu = function (id) {
var i;
var menu = document.getElementById('menu').getElementsByTagName('LI');
var bloqueActual = document.getElementById(id);
for (i = 0; i <= menu.length; i++) { //recorre los LI devolviendolos a su posicion original
menu[i].style.marginLeft = -40;
menu[i].style.opacity = 1;
}
bloqueActual.style.marginLeft = 200;
bloqueActual.style.opacity = 0;
};
})();
and here's my html:
<head>
<meta charset="UTF-8">
<title>Mario Luque Marchena</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/estilos.css">
</head>
<body>
<center>
<h1 class="titulo">Bienvenid#</h1>
</center>
<div id="main-screen">
<ul id="menu">
<center>
<li id="sobremi" onclick="window.animacion_click_menu('sobremi');">Sobre mi</li>
<li id="portafolios" onclick="animacion_click_menu('portafolios');">Portafolios</li>
<li id="animacion" onclick="animacion_click_menu('animacion');">Animacion</li>
<li id="back-end" style="border-bottom-style: dashed;" onclick="animacion_click_menu('back-end');">Back-End</li>
</center>
</ul>
</div>
<script type="text/javascript" src="js/animaciones.js"></script>
</body>
if you have any suggestions to make the code better, are welcome too, i'm learning to code. thank you!, and sorry for the bad english in case it was
Your error is really on the for loop.
Take a look on:
for (i = 0; i <= menu.length; i++) {
it should be:
for (i = 0; i <= menu.length-1; i++) {
Otherwise, it will try to iterate from 0 to 5 while your menu array has only 4 items.
The result is that in the last iteration, when you try to access the element menu with the inexistent index (menu[5]) you get the error:
Uncaught TypeError: Cannot read property 'style' of undefined
Other possibility to overcome this is to change <= to < and work with the loop as:
for (i = 0; i < menu.length; i++) {
use window.onload() or
$('document').ready(function(){
//Put your code here
})
I think your code is getting executed before DOM creation.

Ping-Pong aka FizzBuzz test

I am new to programming and am currently stuck on the Ping-Pong aka FizzBuzz problem. (Make a webpage where the user is prompted to enter a number and every number up to that number is displayed. However, for multiples of three, the page prints "ping," for multiples of five, the page prints "pong," and for multiples of both three and five (15), the page prints "ping-pong.")
I've checked out other solutions on here (such as this one) and they've been helpful for understanding how to solve it. And I hope my javascript reflects that.
My problem is I'm stuck trying to take the input number from the form I have on the webpage and run it through the javascript, if that makes sense.
I'm pretty sure that part of my javascript is just a conglomeration of throwing everything I had at it, which is not the best. Could anyone check out my code and see what I'm doing wrong here?
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.11.2.js"></script>
<script src="js/scripts.js"></script>
<title>Ping-Pong Test</title>
</head>
<body>
<div class="container">
<h1>Ping Pong Test</h1>
<p>Let's play the Ping-Pong game. The Ping-Pong game is a simple test that involves loops, conditionals, and variables. Enter your number below to start</p>
<form id="start-form">
<label for="input-number">Your number:</label>
<input id="input-number" type="number">
<button type="submit" class="btn">Calculate</button>
</form>
<div id="end-number">
<ul id="results"></ul>
</div>
</div>
</body>
</html>
And my javascript:
$(document).ready(function () {
$("#start-form").submit(function(event) {
var a = document.getElementById("#input-number");
var num = a.elements[0].value;
var listItems = "";
var i;
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
console.log("Ping-Pong");
}
else if (i % 3 === 0) {
console.log("Ping");
}
else if (i % 5 === 0) {
console.log("Pong");
}
else{
console.log(i);
};
event.preventDefault();
};
});
Again, I'm new, so if anyone could break it down step by step, I'd really appreciate it. Thanks.
It is not right:
var a = document.getElementById("#input-number");
Must be one of the below lines:
var a = document.getElementById("input-number");
// Or
var a = $("#input-number").get(0);
// Or
var a = $("#input-number")[0];
But it will not solve your problem. Looking deep into your code. I guess you need to have a form an then get the first element:
var a = document.getElementById("start-form");
var num = a.elements[0].value;
But you can simplify even more. Why not just do it:
// remove the a variable
var num = $("#input-number").val(); // get the input-number value
Based on your code I think you just need some syntax cleaned up in order for jquery to use the value from your form.
I took your code, stripped it down for clarity and made a fiddle out of it.
Here is the link:
http://jsfiddle.net/zwa5s3ao/3/
$(document).ready(function(){
$("form").submit(function(event){
var num = $('#input-number').val()
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
$('#list').append('<li>'+"Ping-Pong"+'</li>');}
else if (i % 3 === 0) {
$('#list').append('<li>'+"Ping"+'</li>');}
else if (i % 5 === 0) {
$('#list').append('<li>'+"Pong"+'</li>');}
else{
$('#list').append('<li>'+i+'</li>');}
};
event.preventDefault();
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Ping-Pong Test</title>
<body>
<form>
Your number:
<input type="number" name="input-number" id="input-number">
<input type="submit" value="Calculate">
</form>
<ul id="list"></ul>
</body>
Hope this helps!

Categories

Resources