Compare input value with li content in pure Javascript - javascript

I have to do some kind of ToDo list, where I have input and button to Add item to ul list. And now I done everything except compare every li item with input value. My question is how to compare every li content with value input to prevent duplicate items. Here is the code https://jsfiddle.net/qoLtxfaw/1/
// Variables
var ul = document.getElementById("taskList");
var task = document.getElementById("task");
var btn = document.querySelector('button');
var listItem = document.getElementsByTagName("LI");
// Append close btn to each list item
for (var i = 0; i < listItem.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "js-close";
span.appendChild(txt);
listItem[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("js-close");
for (var i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.className = 'js-hide';
}
}
// proveravati ima li ul odnosno liste, ukoliko ne proverimo a nema ceo kod ce prestati da se izvrsava
if (ul) {
ul.onmouseover = function(event) {
var target = event.target;
target.style.background = '#efebeb';
};
ul.onmouseout = function(event) {
var target = event.target;
target.style.background = '';
};
}
// Add item to list on btn
btn.addEventListener('click', addItem);
// Add item to list on enter
task.onkeyup = function(e) {
if (e.keyCode == 13) {
addItem();
}
};
// // Add item to list
function addItem() {
var li = document.createElement("li");
var inputValue = document.getElementById('task').value;
li.setAttribute('id', task.value);
li.appendChild(document.createTextNode(task.value));
// ul.appendChild(li);
// compare every li item with inputValue
if (inputValue) { //if input value is true and has some value
//go trough all li items
for (var i = 0; i < listItem.length; i++) {
// compare every li item with inputValue
}
// Duplicate values don't allow in list
if (!inputValue) {
alert("No empty values are allowed!");
li.className = 'js-btn-disable';
} else {
ul.appendChild(li);
}
document.getElementById("task").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "js-close";
span.appendChild(txt);
li.appendChild(span);
for (var i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.className = 'js-hide';
}
}
}
}
#wrapper {
width: 500px;
margin: 0 auto;
background: #00bcd4;
border: 1px solid #f1f0f0;
padding-left: 10px;
font-size: 1.2em;
}
#wrapper #task {
background: transparent;
color: #ffffff;
font-size: 1.2em;
width: 80%;
height: 35px;
border: none;
border-bottom: 2px solid #ffffff;
outline: none;
margin: 15px 0 5px 0;
}
#wrapper #task ::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #ffffff;
}
#wrapper #task ::-moz-placeholder {
/* Firefox 19+ */
color: #ffffff;
}
#wrapper #task :-ms-input-placeholder {
/* IE 10+ */
color: #ffffff;
}
#wrapper #task :-moz-placeholder {
/* Firefox 18- */
color: #ffffff;
}
#wrapper button {
font-size: 1.2em;
border: 2px solid #ffffff;
background: transparent;
color: #ffffff;
padding: 5px 10px;
outline: none;
cursor: pointer;
}
#wrapper ul#taskList {
padding: 0;
background: #ffffff;
list-style-type: none;
text-align: left;
margin-bottom: 0;
margin-left: -10px;
}
#wrapper ul#taskList li {
padding: 10px;
position: relative;
cursor: pointer;
}
/* Style the close button */
.js-close {
position: absolute;
right: 0;
top: 0;
padding: 10px;
}
.js-close:hover {
color: #ffffff;
}
.js-hide {
display: none;
}
.js-background {
background: #efebeb;
}
.js-btn-disable {
opacity: 0.65;
cursor: not-allowed;
}
/*# sourceMappingURL=style.css.map */
<div id="wrapper">
<input type="text" id="task" />
<button>Add</button>
<ul id="taskList"></ul>
</div>

Have a look at this. I use firstChild and I moved the validation to the top of the function.
I use the inputValue after validating it but task everywhere else.
DRY - Don't Repeat Yourself
// Variables
var ul = document.getElementById("taskList");
var task = document.getElementById("task");
var btn = document.querySelector('button');
var listItem = document.getElementsByTagName("LI");
task.focus();
// Append close btn to each list item
for (var i = 0; i < listItem.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "js-close";
span.appendChild(txt);
listItem[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("js-close");
for (var i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.className = 'js-hide';
}
}
// proveravati ima li ul odnosno liste, ukoliko ne proverimo a nema ceo kod ce prestati da se izvrsava
if (ul) {
ul.onmouseover = function(event) {
var target = event.target;
target.style.background = '#efebeb';
};
ul.onmouseout = function(event) {
var target = event.target;
target.style.background = '';
};
}
// Add item to list on btn
btn.addEventListener('click', addItem);
// Add item to list on enter
task.onkeyup = function(e) {
if (e.keyCode == 13) {
addItem();
}
};
// // Add item to list
function addItem() {
var inputValue = task.value.trim();
task.value = "";
task.focus();
// Empty or Duplicate values don't allow in list
if (!inputValue) {
alert("No empty values are allowed!");
return
}
var listItem = document.querySelectorAll("#taskList li");
for (var i = 0; i < listItem.length; i++) {
if (inputValue == listItem[i].firstChild.textContent) {
alert("No duplicate values are allowed!");
return
}
}
var li = document.createElement("li");
li.setAttribute('id', inputValue);
li.appendChild(document.createTextNode(inputValue));
ul.appendChild(li);
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "js-close";
span.appendChild(txt);
li.appendChild(span);
for (var i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.className = 'js-hide';
}
}
}
#wrapper {
width: 500px;
margin: 0 auto;
background: #00bcd4;
border: 1px solid #f1f0f0;
padding-left: 10px;
font-size: 1.2em;
}
#wrapper #task {
background: transparent;
color: #ffffff;
font-size: 1.2em;
width: 80%;
height: 35px;
border: none;
border-bottom: 2px solid #ffffff;
outline: none;
margin: 15px 0 5px 0;
}
#wrapper #task ::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #ffffff;
}
#wrapper #task ::-moz-placeholder {
/* Firefox 19+ */
color: #ffffff;
}
#wrapper #task :-ms-input-placeholder {
/* IE 10+ */
color: #ffffff;
}
#wrapper #task :-moz-placeholder {
/* Firefox 18- */
color: #ffffff;
}
#wrapper button {
font-size: 1.2em;
border: 2px solid #ffffff;
background: transparent;
color: #ffffff;
padding: 5px 10px;
outline: none;
cursor: pointer;
}
#wrapper ul#taskList {
padding: 0;
background: #ffffff;
list-style-type: none;
text-align: left;
margin-bottom: 0;
margin-left: -10px;
}
#wrapper ul#taskList li {
padding: 10px;
position: relative;
cursor: pointer;
}
/* Style the close button */
.js-close {
position: absolute;
right: 0;
top: 0;
padding: 10px;
}
.js-close:hover {
color: #ffffff;
}
.js-hide {
display: none;
}
.js-background {
background: #efebeb;
}
.js-btn-disable {
opacity: 0.65;
cursor: not-allowed;
}
/*# sourceMappingURL=style.css.map */
<div id="wrapper">
<input type="text" id="task" />
<button>Add</button>
<ul id="taskList"></ul>
</div>

Related

Unable to edit the label text

I have tried to insert the data into the ToDo List and it is working but i am unable to edit the name and number field in the edit box of ToDo list.
And also the list is showing is not properly having padding and i tried to put padding in the list but whole list is shifting towards the left.
Also I tried with table concept in JavaScript but for that i need the loop and the database but i dont want to use the database or any other storage
var taskInput = document.getElementById("new-task");
var nameInput = document.getElementById("new-name");
var numberInput = document.getElementById("new-number");
var addButton = document.getElementsByTagName("button")[0];
var incompleteTask = document.getElementById("incomplete-tasks");
var completedTask = document.getElementById("completed-tasks");
var createNewTaskElement = function (taskString, nameString, numberString) {
var listItem = document.createElement("li");
var checkBox = document.createElement("input");
var label = document.createElement("label");
var label1 = document.createElement("label1");
var label2 = document.createElement("label2");
var editInput = document.createElement("input");
var editInput1 = document.createElement("input");
var editInput2 = document.createElement("input");
var editButton = document.createElement("button");
var deleteButton = document.createElement("button");
label.innerText = taskString;
label1.innerText = nameString;
label2.innerText = numberString;
checkBox.type = "checkbox";
editInput.type = "text";
editInput1.type = "text";
editInput2.type = "text";
editButton.innerText = "Edit";
editButton.className = "edit";
deleteButton.innerText = "Delete";
deleteButton.className = "delete";
listItem.appendChild(checkBox);
listItem.appendChild(label);
listItem.appendChild(editInput);
listItem.appendChild(label1);
listItem.appendChild(editInput1);
listItem.appendChild(label2);
listItem.appendChild(editInput2);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
alert("You added '" + label.innerText + "' to the ToDO list");
return listItem;
}
var addTask = function () {
var listItem = createNewTaskElement(taskInput.value,nameInput.value,numberInput.value);
if (taskInput.value == "") {
alert("You must enter a task");
}
else if (nameInput.value == "") {
alert("You must enter a Name");
}
else if (numberInput.value == "") {
alert("You must enter a Phone Number");
} else {
incompleteTask.appendChild(listItem);
}
bindTaskEvents(listItem, taskCompleted);
taskInput.value = "";
nameInput.value = "";
numberInput.value = "";
}
var editTask = function () {
var listItem = this.parentNode;
var editInput = listItem.querySelector('input[type=text]');
var label = listItem.querySelector("label");
var containsClass = listItem.classList.contains("editMode");
if (containsClass) {
label.innerText = editInput.value;
alert("You edited " + label.innerText);
} else {
editInput.value = label.innerText;
}
listItem.classList.toggle("editMode");
}
var deleteTask = function () {
var listItem = this.parentNode;
var ul = listItem.parentNode;
alert("You deleted " + listItem.querySelector("label").innerText);
ul.removeChild(listItem);
}
var taskCompleted = function () {
var listItem = this.parentNode;
completedTask.appendChild(listItem);
bindTaskEvents(listItem, taskIncomplete);
alert("You completed " + listItem.querySelector("label").innerText);
}
var taskIncomplete = function () {
var listItem = this.parentNode;
incompleteTask.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
}
var bindTaskEvents = function (taskListItem, checkBoxEventHandler) {
var checkBox = taskListItem.querySelector("input[type=checkbox]");
var editButton = taskListItem.querySelector("button.edit");
var deleteButton = taskListItem.querySelector("button.delete");
editButton.onclick = editTask;
deleteButton.onclick = deleteTask;
checkBox.onchange = checkBoxEventHandler;
}
for (var i = 0; i < incompleteTask.children.length; i++) {
bindTaskEvents(incompleteTask.children[i], taskCompleted);
}
for (var i = 0; i < completedTask.children.length; i++) {
bindTaskEvents(completedTask.children[i], taskIncomplete);
}
var input = document.getElementById("new-number");
input.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
addTask();
}
});
.container {
height: 525px;
width: 450px;
margin: 100px auto;
}
ul {
margin: 0;
padding: 0;
}
li * {
float: left;
}
li,
h3 {
clear: both;
list-style: none;
font-family: Arial, Helvetica, sans-serif;
}
input,button {
outline: none;
}
button {
background: none;
border: 0px;
color: #888;
font-size: 15px;
width: 60px;
margin: 10px 0 0;
font-family: Lato, sans-serif;
cursor: pointer;
}
button:hover {
color: #333;
}
h3, label[for='new-task'] {
color: #333;
font-weight: 700;
font-size: 15px;
border-bottom: 2px solid #333;
padding: 30px 0 10px;
margin: 0;
text-transform: uppercase;
}
input[type="text"] {
margin: 0;
font-size: 18px;
line-height: 18px;
height: 18px;
padding: 10px;
border: 1px solid #ddd;
background: #fff;
border-radius: 8px;
font-family: Lato, sans-serif;
color: #888;
margin-left: 50px;
}
input[type="text"]:focus {
color: #333;
}
label[for='new-task'] {
display: block;
margin: 0 0 20px;
}
input#new-task,#new-name,#new-number {
width: 260px;
margin-bottom: 10px;
}
input:focus{
outline: none;
box-shadow: 0px 0px 5px #61C5FA;
border-color: #5AB0DB;
}
input:hover {
border: 1px solid #999;
border-radius: 5px;
}
p>button:hover {
color: #0FC57C;
}
li {
overflow: hidden;
padding: 20px 0;
border-bottom: 1px solid #eee;
}
li>input[type="checkbox"] {
margin: 0 10px;
position: relative;
top: 15px;
}
li>label {
font-size: 18px;
line-height: 40px;
width: 190px;
padding: 0 0 0 11px;
}
li>input[type="text"] {
width: 180px;
}
#completed-tasks label {
text-decoration: line-through;
color: #888;
}
ul li input[type=text] {
display: none;
}
ul li.editMode input[type=text] {
display: block;
}
ul li.editMode label {
display: none;
}
th{
padding-right: 70px;
}
<!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" type="text/css">
<title>To DO List</title>
</head>
<body style="background-color: #ebeff0">
<div class="container">
<h3 style="text-align: center;">Add Task</h3>
<br>
<label>Add Task</label>
<input id="new-task" type="text" required><br>
<label>Name</label>
<input id="new-name" type="text" required><br>
<label>Phone Number</label>
<input id="new-number" type="text" required><br>
<h3 style="text-align: center;">Todo</h3>
<ul id="incomplete-tasks">
</ul>
<h3 style="text-align: center;">Completed Tasks</h3>
<ul id="completed-tasks">
</ul>
</div>
</body>
<script type="text/javascript" src="main.js"></script>
</html>
I have created the class and then edited the inputs
var taskInput = document.getElementById("new-task");
var nameInput = document.getElementById("new-name");
var numberInput = document.getElementById("new-number");
var addButton = document.getElementsByTagName("button")[0];
var incompleteTask = document.getElementById("incomplete-tasks");
var completedTask = document.getElementById("completed-tasks");
var createNewTaskElement = function (taskString, nameString, numberString) {
var listItem = document.createElement("li");
var checkBox = document.createElement("input");
var label = document.createElement("label");
var label1 = document.createElement("label");
var label2 = document.createElement("label");
var editInput = document.createElement("input");
var editInput1 = document.createElement("input");
var editInput2 = document.createElement("input");
var editButton = document.createElement("button");
var deleteButton = document.createElement("button");
label.innerText = taskString;
label1.innerText = nameString;
label2.innerText = numberString;
label.className = "task";
label1.className = "name";
label2.className = "number";
checkBox.type = "checkbox";
editInput.type = "text";
editInput1.type = "text";
editInput2.type = "text";
editInput.className = "edit";
editInput1.className = "edit1";
editInput2.className = "edit2";
editButton.innerText = "Edit";
editButton.className = "edit";
deleteButton.innerText = "Delete";
deleteButton.className = "delete";
listItem.appendChild(checkBox);
listItem.appendChild(label);
listItem.appendChild(editInput);
listItem.appendChild(label1);
listItem.appendChild(editInput1);
listItem.appendChild(label2);
listItem.appendChild(editInput2);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
alert("You added '" + label.innerText + "' to the ToDO list");
return listItem;
}
var addTask = function () {
var listItem = createNewTaskElement(taskInput.value, nameInput.value, numberInput.value);
if (taskInput.value == "") {
alert("You must enter a task");
} else if (nameInput.value == "") {
alert("You must enter a Name");
} else if (numberInput.value == "") {
alert("You must enter a Phone Number");
} else {
incompleteTask.appendChild(listItem);
}
bindTaskEvents(listItem, taskCompleted);
taskInput.value = "";
nameInput.value = "";
numberInput.value = "";
}
var editTask = function () {
var listItem = this.parentNode;
var editInput = listItem.querySelector('.edit');
var editInput1 = listItem.querySelector('.edit1');
var editInput2 = listItem.querySelector('.edit2');
var label = listItem.querySelector(".task");
var label1 = listItem.querySelector(".name");
var label2 = listItem.querySelector(".number");
var containsClass = listItem.classList.contains("editMode");
if (containsClass) {
label.innerText = editInput.value;
label1.innerText = editInput1.value;
label2.innerText = editInput2.value;
alert("You edited " + label.innerText);
} else {
editInput.value = label.innerText;
editInput1.value = label1.innerText;
editInput2.value = label2.innerText;
}
listItem.classList.toggle("editMode");
}
var deleteTask = function () {
if (confirm("Are you sure you want to delete this task?") == true) {
var listItem = this.parentNode;
var ul = listItem.parentNode;
alert("You deleted " + listItem.querySelector("label").innerText);
} else {
alert("You cancelled the task");
}
ul.removeChild(listItem);
}
var taskCompleted = function () {
var listItem = this.parentNode;
if (confirm("Are you sure you want to mark this task as complete?") == true) {
completedTask.appendChild(listItem);
bindTaskEvents(listItem, taskIncomplete);
alert("You completed " + listItem.querySelector("label").innerText);
} else {
alert("You cancelled the task");
}
}
var taskIncomplete = function () {
var listItem = this.parentNode;
incompleteTask.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
}
var bindTaskEvents = function (taskListItem, checkBoxEventHandler) {
var checkBox = taskListItem.querySelector("input[type=checkbox]");
var editButton = taskListItem.querySelector("button.edit");
var deleteButton = taskListItem.querySelector("button.delete");
editButton.onclick = editTask;
deleteButton.onclick = deleteTask;
checkBox.onchange = checkBoxEventHandler;
}
for (var i = 0; i < incompleteTask.children.length; i++) {
bindTaskEvents(incompleteTask.children[i], taskCompleted);
}
for (var i = 0; i < completedTask.children.length; i++) {
bindTaskEvents(completedTask.children[i], taskIncomplete);
}
var input = document.getElementById("new-number");
.container {
height: 525px;
width: 700px;
margin: 100px auto;
}
ul {
margin: 0;
padding: 0;
}
li * {
float: left;
}
li,
h3 {
clear: both;
list-style: none;
font-family: Arial, Helvetica, sans-serif;
}
input,button {
outline: none;
}
button {
background: none;
border: 0px;
color: #888;
font-size: 15px;
width: 60px;
margin: 10px 0 0;
font-family: Lato, sans-serif;
cursor: pointer;
}
button:hover {
color: #333;
}
h3, label[for='new-task'] {
color: #333;
font-weight: 700;
font-size: 15px;
border-bottom: 2px solid #333;
padding: 30px 0 10px;
margin: 0;
text-transform: uppercase;
}
input[type="text"] {
margin: 0;
font-size: 18px;
line-height: 18px;
height: 18px;
padding: 10px;
border: 1px solid #ddd;
background: #fff;
border-radius: 8px;
font-family: Lato, sans-serif;
color: #888;
margin-left: 50px;
}
input[type="text"]:focus {
color: #333;
}
label[for='new-task'] {
display: block;
margin: 0 0 20px;
}
input#new-task,#new-name,#new-number {
width: 260px;
margin-bottom: 10px;
}
input:focus{
outline: none;
box-shadow: 0px 0px 5px #61C5FA;
border-color: #5AB0DB;
}
input:hover {
border: 1px solid #999;
border-radius: 5px;
}
p>button:hover {
color: #0FC57C;
}
li {
overflow: hidden;
padding: 20px 0;
border-bottom: 1px solid #eee;
}
li>input[type="checkbox"] {
margin: 0 10px;
position: relative;
top: 15px;
}
li>label {
font-size: 18px;
line-height: 40px;
width: 100px;
padding: 0 0 0 11px;
}
li>input[type="text"] {
width: 100px;
}
li>button{
padding-left: 3px;
}
li>button:hover{
border: 1px solid black;
color: #c54f0f;
}
#completed-tasks label {
text-decoration: line-through;
color: #888;
}
ul li input[type=text] {
display: none;
}
ul li.editMode input[type=text] {
display: block;
}
ul li.editMode label {
display: none;
}
#AddBtn{
align-items: center;
border: 1px solid black !important;
background-color: white;
}
<!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" type="text/css">
<title>To DO List</title>
</head>
<body style="background-color: #ebeff0">
<div class="container">
<h3 style="text-align: center;">Add Task</h3>
<br>
<label>Add Task</label>
<input id="new-task" type="text" required><br>
<label style="padding-right: 05px;">Name</label>
<input id="new-name" type="text" required><br>
<label>Phone Number</label>
<input id="new-number" type="text" required><br>
<button id="AddBtn" onclick="addTask()">Add</button>
<h3 style="text-align: center;">Todo</h3>
<ul id="incomplete-tasks">
</ul>
<h3 style="text-align: center;">Completed Tasks</h3>
<ul id="completed-tasks">
</ul>
</div>
</body>
<script type="text/javascript" src="main.js"></script>
</html>

How do I trigger the "Add" button after pressing enter in the textbox?

I created a to-do list so when you add something into the textbox and click the add button it adds it into the list which is shown below it. However, I want to quickly add a bunch of things and not tediously use my mouse to click the add button every time, that's why I have been trying to add in the function for when I press enter it will be added. But everything I've tried hasn't been working and yes I've read through and attempted to use code from other questions on stackoverflow which is why I've finally decided to ask this question.
Please help! [the end of the JavaScript part of the snippet is my most recent attempt]
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
window.addEventListener('keyup', function (e) {
if (e.keyCode === 13) {
var button = document.getElementById("myInput");
button.click();
}
}, false);
}
body {
background-color: #81B9E3;
font-family: 'Handlee', cursive;
}
h1 {
color: #2F90DA;
font-size: xxx-large;
font-family: 'Concert One', cursive;
}
a {
text-decoration: none;
color: #2F90DA;
}
p{
color: black;
}
body {
margin: 0;
min-width: 250px;
}
/* Include the padding and border in an element's total width and height */
* {
box-sizing: border-box;
}
/* Remove margins and padding from the list */
ul {
margin: 0;
padding: 0;
}
/* Style the list items */
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: none;
background: #7DB9FF;
font-size: 18px;
transition: 0.2s;
/* make the list items unselectable */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Set all odd list items to a different color (zebra-stripes) */
ul li:nth-child(odd) {
background: #93C5FF;
}
/* Darker background-color on hover */
ul li:hover {
background: #51CA4C;
}
/* When clicked on, add a background color and strike out text */
ul li.checked {
background: #9DF599;
color: #51CA4C;
text-decoration: line-through;
}
/* Add a "checked" mark when clicked on */
ul li.checked::before {
content: '';
position: absolute;
border-color: #51CA4C;
border-style: solid;
border-width: 0 2px 2px 0;
top: 10px;
left: 16px;
transform: rotate(45deg);
height: 15px;
width: 7px;
}
/* Style the close button */
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close:hover {
background-color: #F44336;
color: white;
}
/* Style the header */
.header {
background-color: #2F90DA;
padding: 30px 40px;
color: white;
text-align: center;
}
/* Clear floats after the header */
.header:after {
content: "";
display: table;
clear: both;
}
/* Style the input */
input {
margin: 0;
border: none;
border-radius: 0;
width: 75%;
padding: 10px;
float: left;
font-size: 16px;
}
/* Style the "Add" button */
.addBtn {
padding: 8.5px;
width: 25%;
background: #81B9E3;
color: #fff;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
border-radius: 0;
}
.addBtn:hover {
background-color: #51CA4C;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>To Do List</title>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Actor&family=Luckiest+Guy&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Concert+One&family=Handlee&family=Actor&display=swap" rel="stylesheet">
<link href="todo.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div style="background-color: #DCEEF5; padding: 20px; text-align: center;">
<h1> 📖 To Do List 📖</h1>
<h2 style="margin-top: 0; margin-left: 20%; margin-right: 20%">Make your own to do list!</h2>
<h3>Type your task and click "Add". Once your task is completed, just click on the task to cross it off. Press the x button on the far right of a task to remove it.</h3>
<h4 style="margin-bottom: 3%;">Go back to Productify Home or Navigation</h4>
</div><br/>
</body>
<style>
</style>
</head>
<body>
<div id="myDIV" class="header">
<h2 style="margin:5px">📖 My To Do List 📖</h2>
<input type="text" id="myInput" placeholder="New Task...">
<span onclick="newElement()" class="addBtn">Add</span>
</div>
<ul id="myUL"></ul>
<script src="todo.js"></script>
</body>
</html>
You can probably get away with using the same handler for both the button and the input using a closure.
// Cache your elements
const input = document.querySelector('input');
const list = document.querySelector('div');
const button = document.querySelector('button');
// Pass in the input and list elements to the handler
// The handler returns a new function that will be used
// for both the button and input listeners
const handler = handleInput(input, list);
button.addEventListener('click', handler, false);
input.addEventListener('keyup', handler, false);
function handleInput(input, list) {
// Initialise the text in the input
let text = '';
// Add the text to the page, reset `text`,
// and reset the input value
function printLine(text) {
list.innerHTML += `<div>${text}</div>`;
text = '';
input.value = '';
}
// This is the listener
return function(e) {
const { code, target: { value, type } } = e;
// If the button is clicked call `printLine`
if (type === 'submit') printLine(text);
// If the input has changed
// If return has been pressed call printLine
// otherwise update the text value
if (type === 'text') {
if (code === 'Enter') {
printLine(text);
} else {
text = value;
}
}
}
}
<input />
<button>Add to list</button>
<div></div>

Javascript [object HTMLCollection] [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Using Javascript I am creating a list website (as a side-project).
I use the code:
var myNodelist = document.getElementsByTagName("LI");
and that works, but
localStorage.setItem("myNodelist", document.getElementsByTagName("LI"));
doesn't. it just returns [object HTMLCollection]. Does anyone know why?
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
min-width: 250px;
}
/* Include the padding and border in an element's total width and height */
* {
box-sizing: border-box;
}
/* Remove margins and padding from the list */
ul {
margin: 0;
padding: 0;
}
/* Style the list items */
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: none;
background: #eee;
font-size: 18px;
transition: 0.2s;
/* make the list items unselectable */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Set all odd list items to a different color (zebra-stripes) */
ul li:nth-child(odd) {
background: #f9f9f9;
}
/* Darker background-color on hover */
ul li:hover {
background: #ddd;
}
/* When clicked on, add a background color and strike out text */
ul li.checked {
background: #888;
color: #fff;
text-decoration: line-through;
}
/* Add a "checked" mark when clicked on */
ul li.checked::before {
content: '';
position: absolute;
border-color: #fff;
border-style: solid;
border-width: 0 2px 2px 0;
top: 10px;
left: 16px;
transform: rotate(45deg);
height: 15px;
width: 7px;
}
/* Style the close button */
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close:hover {
background-color: #168e00;
color: white;
}
/* Style the header */
.header {
background-color: #168e00;
padding: 30px 40px;
color: white;
text-align: center;
}
/* Clear floats after the header */
.header:after {
content: "";
display: table;
clear: both;
}
/* Style the input */
input {
margin: 0;
border: none;
border-radius: 0;
width: 75%;
padding: 10px;
float: left;
font-size: 16px;
}
/* Style the "Add" button */
.addBtn {
padding: 10px;
width: 25%;
background: #d9d9d9;
color: #555;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
border-radius: 0;
}
.addBtn:hover {
background-color: #bbb;
}
</style>
</head>
<body>
<div id="myDIV" class="header">
<h2 style="margin:5px">Groceries:</h2>
<input type="text" id="myInput" placeholder="Title...">
<span onclick="newElement()" class="addBtn">Add</span>
</div>
<ul id="myUL">
</ul>
</body>
</html>
If you write var Lists = document.getElementsByTagName("List"); in your console.log(list) you will see the list of elements that you need right ?
The console.log also shows array the same way ,each element of an array is print to the log without you having to write a for() loop.
However if you want to use the array you have to write the for loop
[object HTMLCollection]
means that there is an array of HTML objects, To work with the data you have to use a for loop or array methods so before storing it in local storage
Try Make an array with the object collection with
var arr = Array.from(htmlCollection);
Then save as is or convert to json string with
var myJsonString = JSON.stringify(arr);
I trust this helps
First: its better if you use id to find the dom element from DOM API.
Second: you need to use .innerText to access the text content of list item.
<ul>
<li id="item">hello</li>
</ul>
localStorage.setItem("myNodelist",document.getElementById("item").innerText);

Search/Filter Dropdown Javascript

I'm following this guide to create Search/Filter Dropdown.
But I have this method 'allNameMuseums()', that returns an array of names (for example :
array = ["Jack", "Paul", "George"]
My JS code :
async function allNameMuseums() {
let nomeFile = "dati_musei_infovis.csv";
let data3 = await d3.dsv(";", nomeFile, function (d) {
return {
Museo: d.Museo,
Ingresso: d.Ingresso,
Anno: d.Anno,
Mese: d.Mese,
Visitatori: d.Visitatori
};
});
return filtraggioNomeMuseo(data3);
};
function filtraggioNomeMuseo(data) {
array_filtrato = [];
var map = {};
//var visitatori = 0;
for (i=0; i<data.length; i++) {
if (!(array_filtrato.includes(data[i].Museo))) {
array_filtrato.push(data[i].Museo)
}
}
return array_filtrato;
}
I want to put these names instead of About, Base, Blog etc...
You could loop through the returned array and append the names as anchors to the dropdown like :
document.addEventListener("DOMContentLoaded", function(event) {
allNameMuseums().forEach(function(item){
document.getElementById("myDropdown").innerHTML += ''+item+'';
})
});
NOTE: Put your code inside DOMContentLoaded event listener to make sure all the DOM elements are loaded before executing your code/
Working sample:
document.addEventListener("DOMContentLoaded", function(event) {
allNameMuseums().forEach(function(item) {
document.getElementById("myDropdown").innerHTML += '' + item + '';
})
});
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
function allNameMuseums() {
return ["Jack", "Paul", "George"];
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover,
.dropbtn:focus {
background-color: #3e8e41;
}
#myInput {
border-box: box-sizing;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
#myInput:focus {
outline: 3px solid #ddd;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
</div>
</div>

Custom popup with .onclick is not working

So I am working on creating a custom alert box. I've got most of the code the way I want it.
What I Want:
What I would like is to click the minus to fade the alert box so you can view the html behind it.
What is Wrong:
My issue is the min.onclick code does not click (clicking the minus sign does nothing).
See Below:
var b = document.getElementById('button-container');
var bg = document.createElement('div');
bg.setAttribute('id', 'alert-box');
bg.setAttribute('class','alert');
b.appendChild(bg);
var box = document.createElement('div');
box.setAttribute('id', 'alert-text');
box.setAttribute('class','alert-content');
box.setAttribute('display', 'block');
box.innerHTML = 'Fancy stuff happens here!<br>Look chess pieces';
bg.appendChild(box);
var min = document.createElement('span');
min.setAttribute('id','alert-min');
min.setAttribute('class','alert-min');
min.innerHTML = '−';
var s = true;
min.onclick = function() {
console.log('pressed!');
if(s) {
box.style.opacity = '.25';
s = false;
}
else{
box.style.opacity = '1';
s = true;
}
};
box.appendChild(min);
box.innerHTML += '<br><br>';
var images = ['q', 'n', 'r', 'b'];
var t = ['1/15', '7/70', '7/72', 'b/b1'];
for(var i = 0; i < images.length; i++) (function(i){
var btn = document.createElement('button');
btn.setAttribute('class','alert-button');
btn.setAttribute('id',images[i]+'btn');
btn.onclick = function () {
console.log('You clicked: ', images[i]);
};
box.appendChild(btn);
var img = document.createElement('img');
img.setAttribute('id',images[i]+'img');
img.setAttribute('src','https://upload.wikimedia.org/wikipedia/commons/thumb/'+t[i]+'/Chess_'+images[i]+'lt45.svg/45px-Chess_'+images[i]+'lt45.svg.png');
img.setAttribute('class','alert-image');
btn.appendChild(img);
})(i);
.alert {
display: block;
position: fixed;
z-index: 1;
padding-top: 10px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.alert-content {
background-color: #daac27;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.alert-min {
color: #fff;
float: right;
font-size: 28px;
font-weight: bold;
}
.alert-min:hover,
.alert-min:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<br><br><br>
O no! You can't see me!
<div id="button-container">
</div>
To be honest I have no idea why your script does not work. I did nothing but appending the close "button" after that loop. Now the click handler is working.
edit:
i also edited the other console.log due to it printed undefined
var b = document.getElementById('button-container');
var bg = document.createElement('div');
bg.setAttribute('id', 'alert-box');
bg.setAttribute('class','alert');
b.appendChild(bg);
var box = document.createElement('div');
box.setAttribute('id', 'alert-text');
box.setAttribute('class','alert-content');
box.setAttribute('display', 'block');
box.innerHTML = 'Fancy stuff happens here!<br>Look chess pieces';
bg.appendChild(box);
box.innerHTML += '<br><br>';
var images = ['q', 'n', 'r', 'b'];
var t = ['1/15', '7/70', '7/72', 'b/b1'];
for(var i = 0; i < images.length; i++) {
var btn = document.createElement('button');
btn.setAttribute('class','alert-button');
btn.setAttribute('id',images[i]+'btn');
let tmp = images[i]
btn.onclick = function () {
console.log('You clicked: ', tmp);
};
box.appendChild(btn);
var img = document.createElement('img');
img.setAttribute('id',images[i]+'img');
img.setAttribute('src','https://upload.wikimedia.org/wikipedia/commons/thumb/'+t[i]+'/Chess_'+images[i]+'lt45.svg/45px-Chess_'+images[i]+'lt45.svg.png');
img.setAttribute('class','alert-image');
btn.appendChild(img);
}
var min = document.createElement('span');
min.setAttribute('id','alert-min');
min.setAttribute('class','alert-min');
min.innerHTML = '−';
var s = true;
min.onclick = function() {
console.log('pressed!');
if(s) {
box.style.opacity = '.25';
s = false;
}
else{
box.style.opacity = '1';
s = true;
}
};
box.appendChild(min);
.alert {
display: block;
position: fixed;
z-index: 1;
padding-top: 10px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.alert-content {
background-color: #daac27;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.alert-min {
color: #fff;
float: right;
font-size: 28px;
font-weight: bold;
}
.alert-min:hover,
.alert-min:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<br><br><br>
O no! You can't see me!
<div id="button-container">
</div>

Categories