Creating a Multi level list - javascript

I am using contenteditable where I am trying to add if the the tab key is pressed for it to indent forward 1 row then second row etc. I have only been able to get it to indent out only 1 row but not sure on how to expand on it. My code may not be the right method to take.
const TAB_KEY = 9;
const ENTER_KEY = 13;
const SHIFT_KEY = 16
const editor = document.querySelector('.editor');
editor.appendChild(document.createElement('li'));
editor.addEventListener('keydown', (e) => {
let code = e.keyCode || e.which;
if (code == TAB_KEY) {
e.preventDefault();
let parent = e.target;
let ul = document.createElement('ul');
let li = document.createElement('li');
ul.appendChild(li);
parent.appendChild(ul);
moveCursorToEnd(li);
} else if (code == ENTER_KEY) {
e.preventDefault();
let parent = e.target;
let li = document.createElement('li');
parent.appendChild(li);
moveCursorToEnd(li);
}
});
function moveCursorToEnd(el) {
el.focus();
document.execCommand('selectAll', false, null);
document.getSelection().collapseToEnd();
}
/*editor.addEventListener('click', (x) => {
x = document.getElementById("b");
if(x.style.fontWeight == "bolder"){
x.style.fontWeight = "normal";
} else {
x.style.fontWeight = "bolder";
}
});*/
function bold(){
if(document.execCommand("bold")){
document.execCommand("normal");
}else{
document.execCommand("bold");
}
}
/*function underline(){
let x = document.getElementById("text");
if(x.style.textDecoration == "underline"){
x.style.textDecoration = "none";
}else{
x.style.textDecoration = "underline";
}
}*/
function underline(){
if(document.execCommand("underline")){
document.execCommand("none");
}else{
document.execCommand("underline");
}
}
/*function italic(){
let x = document.getElementById("text");
if(x.style.fontStyle == "italic"){
x.style.fontStyle = "normal";
}else{
x.style.fontStyle = "italic";
}
}*/
/*Turns the font of the text to Italic*/
function italic(){
if(document.execCommand("italic")){
document.execCommand("normal");
}else{
document.execCommand("italic");
}
}
function highlighSelectedText(){
let sel = window.getSelection().getRangeAt(0);
let selText = sel.extractContents();
let span = document.createElement("span");
span.style.backgroundColor = "yellow";
span.appendChild(selText);
sel.insertNode(span);
}
/*function printPage(){
let printButton = document.getElementById("ul");
printButton.style.visibility = 'hidden';
window.print();
printButton.style.visibility = 'visible';
}*/
body{
margin-top:1em;
margin-bottom: 10em;
margin-right: 1em;
margin-left: 1em;
border: solid;
border-color: #0033cc;
background-color: #f6f6f6;
}
div button{
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
div input{
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
div{
list-style-type:square;
list-style-position: inside;
margin-left: 0.25em;
margin-bottom: 5em;
}
section {
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
.editor {
font-weight: normal;
}
div contenteditable{
margin-bottom: 10em;
}
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<head>
<title>Outliner</title>
<link href="style.css" rel="stylesheet" title="Style">
<div>
<button id="b" onclick="bold()"> B </button>
<button onclick="underline()"> U </button>
<button onclick="italic()"> I </button>
<input type="button" onclick="highlighSelectedText()" value="Highlight"/>
<input id="color" type="color">
<button onclick="document.getElementById('text').style.color = document.getElementById('color').value">Set Colour</button>
<div id="text" class="editor" contenteditable="true" draggable="true"></div>
</div>
</head>
<script type= "text/javascript" src='setting.js'></script>
</body>

Related

Add score board in ti-tac-toe game

var grid = document.getElementById('grid');
var msg = document.querySelector('.message');
var chooser = document.querySelector('form');
var mark;
var cells;
// add click listener to radio buttons
function setPlayer() {
mark = this.value;
msg.textContent = mark + ', click on a square to make your move!';
chooser.classList.add('game-on');
this.checked = false;
buildGrid();
}
// add click listener to each cell
function playerMove() {
if (this.textContent == '') {
this.textContent = mark;
checkRow();
switchMark();
computerMove();
}
}
// let the computer make the next move
function computerMove() {
var emptyCells = [];
var random;
/* for (var i = 0; i < cells.length; i++) {
if (cells[i].textContent == '') {
emptyCells.push(cells[i]);
}
}*/
cells.forEach(function(cell){
if (cell.textContent == '') {
emptyCells.push(cell);
}
});
// computer marks a random EMPTY cell
random = Math.ceil(Math.random() * emptyCells.length) - 1;
emptyCells[random].textContent = mark;
checkRow();
switchMark();
}
// switch player mark
function switchMark() {
if (mark == 'X') {
mark = 'O';
} else {
mark = 'X';
}
}
// determine a winner
function winner(a, b, c) {
if (a.textContent == mark && b.textContent == mark && c.textContent == mark) {
msg.textContent = mark + ' is the winner!';
a.classList.add('winner');
b.classList.add('winner');
c.classList.add('winner');
return true;
} else {
return false;
}
}
// check cell combinations
function checkRow() {
winner(document.getElementById('c1'), document.getElementById('c2'), document.getElementById('c3'));
winner(document.getElementById('c4'), document.getElementById('c5'), document.getElementById('c6'));
winner(document.getElementById('c7'), document.getElementById('c8'), document.getElementById('c9'));
winner(document.getElementById('c1'), document.getElementById('c4'), document.getElementById('c7'));
winner(document.getElementById('c2'), document.getElementById('c5'), document.getElementById('c8'));
winner(document.getElementById('c3'), document.getElementById('c6'), document.getElementById('c9'));
winner(document.getElementById('c1'), document.getElementById('c5'), document.getElementById('c9'));
winner(document.getElementById('c3'), document.getElementById('c5'), document.getElementById('c7'));
}
// clear the grid
function resetGrid() {
mark = 'X';
/* for (var i = 0; i < cells.length; i++) {
cells[i].textContent = '';
cells[i].classList.remove('winner');
}*/
cells.forEach(function(cell){
cell.textContent = '';
cell.classList.remove('winner');
});
msg.textContent = 'Choose your player:';
chooser.classList.remove('game-on');
grid.innerHTML = '';
}
// build the grid
function buildGrid() {
for (var i = 1; i <= 9; i++) {
var cell = document.createElement('li');
cell.id = 'c' + i;
cell.addEventListener('click', playerMove, false);
grid.appendChild(cell);
}
/* cells = document.querySelectorAll('li'); //Returns a NodeList, not an Array
See https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches */
cells = Array.prototype.slice.call(grid.getElementsByTagName('li'));
}
var players = Array.prototype.slice.call(document.querySelectorAll('input[name=player-choice]'));
players.forEach(function(choice){
choice.addEventListener('click', setPlayer, false);
});
var resetButton = chooser.querySelector('button');
resetButton.addEventListener('click', function(e) {
e.preventDefault();
resetGrid();
});
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
background-color: #996E89;
font-family: "Comfortaa", sans-serif;
}
h1 {
font-family: "Lobster", serif;
}
.message {
color: #fff;
font-size: 1.5em;
padding-bottom: 1em;
}
form {
label {
font-size: 4em;
font-weight: bold;
vertical-align: middle;
}
input[type=radio] {
margin: 1em;
cursor: pointer;
}
fieldset {
display: block;
opacity: 1;
transition: all ease 1s;
}
&.game-on fieldset {
opacity: 0;
display: none;
}
&.game-on button {
opacity: 1;
display: block;
margin: 0 auto;
}
}
#grid-section {
margin: 3em 0;
}
#grid {
width: 300px;
margin: 0 auto;
}
li {
border: 1px solid #000;
width: 100px;
height: 100px;
display: block;
float: left;
font-size: 3em;
text-align: center;
padding: .5em;
}
#c1, #c2, #c3 {
border-top: none;
}
#c3, #c6, #c9 {
border-right: none;
}
#c7, #c8, #c9 {
border-bottom: none;
}
#c1, #c4, #c7 {
border-left: none;
}
.winner {
color: #9AE1E5;
}
.btn-primary,
.btn-primary:focus {
background-color: #33B7A5;
opacity: 0;
outline: 0;
transition: all ease .3s;
}
.btn-primary:hover {
background-color: #4C2F39;
}
<div class="container">
<div class="row text-center" id="intro-section">
<h1>Player vs Computer Tic-Tac-Toe</h1>
<h2 class="message">Choose your player:</h2>
<form action="#">
<fieldset>
<input type="radio" name="player-choice" id="player-choice-1" value="X" />
<label for="player-choice-1">X</label>
<input type="radio" name="player-choice" id="player-choice-2" value="O" />
<label for="player-choice-2">O</label>
</fieldset>
<button id="reset" class="btn btn-primary">Reset</button>
</form>
</div>
<div class="row" id="grid-section">
<ul id="grid"></ul>
</div>
I wish to add a scoreboard on top where wins,loses,draws would be calculated. How do I go about the same? Also an another HTML page where I could see the number of wins, loses, draws.
I have tried adding table in the html and using it in JS but not able to implement the same.
Could you suggest any methods to implement these tasks in the project.

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>

Drop-down select option with filter and navigation by keys

I want to build a dropdown select option menu with filter and I want to be able to filter by keys and use Enter key to select or to use the mouse in order to select.
The code I wrote is bellow and I am stuck. How can I make the options act just like I am using mouse and click when I filter and use arrow keys and enter? I hope you understand me, English is not my first language.
Should I rethink the code? I want to use pure javascript, so jQuery or other framework wont help.
Thanks for your help.
I created a jsfiddle too: https://jsfiddle.net/rscj2tuv/
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
#myInput {
box-sizing: border-box;
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: 200px;
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;}
.dropdown a:focus {background-color: #ddd;}
.show {display: block;}
.selected {
background:#efefef;
}
</style>
</head>
<body>
<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>
<input name='fname' type='text' placeholder='220' value='' readonly="readonly" size='1'>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn"><span id="ajaxify">Dropdown</span></button>
<div id="myDropdown" class="dropdown-content" style="height: 200px; overflow-x: hidden; overflow-y: scroll;">
<input type="text" placeholder="Search..." id="myInput" onkeyup="filterFunction()">
<a onclick="toyFunction('22','About')">About</a>
<a onclick="toyFunction('32','Base')">Base</a>
<a onclick="toyFunction('42','Blog')">Blog</a>
<a onclick="toyFunction('52','Go')">Go</a>
<a onclick="toyFunction('62','Out')">Out</a>
<a onclick="toyFunction('72','Now')">Now</a>
</div>
</div>
<span id="ajaxify1">Dropdown</span>
<script>
function myFunction(){
document.getElementById("myDropdown").classList.toggle("show");
document.getElementById("myInput").focus();
}
function toyFunction(cat,name) {
xx = document.getElementById("myDropdown");
xx.classList.toggle("show");
document.getElementsByName('fname')[0].value=cat;
document.getElementById("ajaxify").innerHTML = name;
document.getElementById("myInput").value = "";
a = xx.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
a[i].style.display = "block";
}
loadXmlDoc(cat);
}
function loadXmlDoc(fname){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify1").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname=" + fname);
}
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++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
xx = document.getElementById("myDropdown");
var input = document.getElementById("myInput");
var a = xx.getElementsByTagName("a");
var options = Array.from(xx.getElementsByTagName("a")).map(function(el){
return el.innerHTML;
});
var zz='0';
xx = document.getElementById("myDropdown");
var input = document.getElementById("myInput");
var a = xx.getElementsByTagName("a");
var options = Array.from(a).map(function(el){
return el.innerHTML;
});
input.addEventListener('keypress', function(e){
if(e.keyCode == 13){
var a = options.filter(function(a){
return a.toLowerCase().includes(input.value.toLowerCase());
});
if(a.length > 0){
xx = document.getElementById("myDropdown");
xx.classList.toggle("show");
document.getElementsByName('fname')[0].value=a[zz];
document.getElementById("ajaxify").innerHTML = name;
document.getElementById("myInput").value = "";
a = xx.getElementsByTagName("a");
}
}
});
input.addEventListener('keydown', function(e){
for (i = 0; i < a.length; i++) {
a[zz].style.cssText = '';
}
if(e.keyCode == 40){
++zz;
if(zz==options.length){
zz='0';
}
a[zz].style.backgroundColor = '#ddd';
document.getElementsByName('fname')[0].value=options[zz];
}
else if(e.keyCode == 38){
--zz;
if(zz<'0'){
zz=options.length-1;
}
a[zz].style.backgroundColor = '#ddd';
document.getElementsByName('fname')[0].value=options[zz];
}
});
</script>
</body>
</html>
I have rewritten the script and it works. This is the link to the script.
https://codereview.stackexchange.com/questions/235178/drop-down-menu-with-autofilter-and-click-enter-for-selection-and-navigation-by-m

how to modify existing object inside an array in localstorage

I have an array that contains objects and then the array is stored in localStorage. I want to be able to modify variable inside an the object after it's been stored in localStorage. The item I want to modify is when detecting the corresponding checkbox being checked, I want to change the status of that checkbox from false to true. What's the best way to do that. here's the code
<!DOCTYPE html>
<html>
<head>
<title>TodoList App</title>
<!-- bootstrap cdn -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- google fonts -->
<link href="https://fonts.googleapis.com/css?family=Righteous" rel="stylesheet">
<style type="text/css">
/*variables*/
:root {
--righteous-font: 'Righteous', cursive;
}
body {
/*background-color: #536691;*/
background-image: url("http://pctechtips.org/apps/todo/img/Chicago-Wallpaper-3.jpg");
min-height: 100vh;
z-index: -10;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
color: white;
font-size: 1.3rem;
}
.hero {
position: absolute;
min-height: 100vh;
min-width: 100vw;
top: 0;
bottom: 0;
background-color: rgba(31, 34, 118, 0.5);
}
h1 {
margin-top: 12rem;
margin-bottom: 0px;
padding-bottom: 0px;
font-family: var(--righteous-font);
}
.lead {
font-size: 1.5rem;
font-family: var(--righteous-font);
}
/*hr {
margin-top: 2rem;
border: 1px solid white
}*/
ul {
/*border-top: 2px solid white;*/
margin-top: 2rem;
list-style: none;
/*display: none;*/
}
li {
border-bottom: 1px solid white;
padding: 0.5rem 0 0.5rem 0;
margin: 0 1rem 0 1rem;
}
.checkboxes {
float: right;
line-height: 15px;
width: 17px;
height: 17px;
background-color: #e9ecef;
border: 1px solid #e9ecef;
border-radius: 3px;
}
</style>
</head>
<body>
<div class="hero">
<div class="container">
<h1 class="display-2 text-center">TodoList</h1>
<p class="lead text-center">Welcome to my todoList applications</p>
<div class="row">
<form id="form" class="col-8 mx-auto">
<div class="input-group">
<input id="input" class="form-control" placeholder="Enter todo list item" value="this is a todo item list">
<span>
<button id="btn" type="button" class="btn btn-primary">Submit</button>
</span>
</div>
</form>
</div>
<div class="row">
<ul id="list" class="list col-8 mx-auto">
<!-- <li>this is a todo item <input type="checkbox" class="checkbox"></li>
<li>this is a todo item <input type="checkbox" class="checkbox"></li> -->
</ul>
</div>
</div>
</div>
<script type="text/javascript">
window.onload = function() {
//variables
var list = document.getElementById("list");
var input = document.getElementById("input");
var btn = document.getElementById('btn');
var id = 1;
var todoList = [];
//{item: "item", isChecked: "false"};
var todoItem = "";
//button event listener
btn.addEventListener("click", addTodoItem);
//list event listener for checkbox
list.addEventListener("click", boxChecked);
if(localStorage.length > 0) {
displayList();
}
//add todo list item
function addTodoItem() {
if(input.value === "") {
alert("Input field can't be empty!");
}
else {
if(list.style.borderTop === "") {
list.style.borderTop = "2px solid white";
}
var li = document.createElement("li");
var text = document.createTextNode(input.value);
li.id = "li-"+id;
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.className = "checkboxes"
checkbox.id = "box-"+id;
li.appendChild(text);
li.appendChild(checkbox);
list.appendChild(li);
id++;
addToLocalStorage();
}
}
//adding strike through style when checkbox clicked
function boxChecked(event) {
const element = event.target;
//ignore clicks on anything else other than checkbox
if(element.type !== "checkbox") return;
console.log(element.id);
//apply css style
element.parentNode.style.textDecoration = "line-through";
}
//adding items to localstorage
function addToLocalStorage() {
console.log(localStorage.toString());
todoItem = {item: input.value, isChecked: "false"};
todoList.push(todoItem);
//checking localsotorage exists
if(typeof(Storage) !== "undefined") {
localStorage.setItem("todoList", JSON.stringify(todoList));
}
else {
alert("localstorage not available in browser!");
}
}
/* display all todo list items */
function displayList() {
todoList = JSON.parse(localStorage.getItem("todoList"));
list.style.borderTop = "2px solid white";
for(var i = 0; i < todoList.length; i++) {
var li = document.createElement("li");
var text = document.createTextNode(todoList[i].item);
li.id = "li-"+id;
var checkbox = document.createElement("input");
/*if(Boolean(todoList[i].isChecked)) {
checkBox.checked = true;
checkBox.style.textDecoration = "line-through";
}*/
checkbox.type = "checkbox";
checkbox.className = "checkboxes"
checkbox.id = "box-"+id;
li.appendChild(text);
li.appendChild(checkbox);
list.appendChild(li);
id++;
}
}
}
</script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
</body>
</html>
I would make that inside the boxChecked function:
function boxChecked(event) {
const element = event.target;
//ignore clicks on anything else other than checkbox
if(element.type !== "checkbox") return;
var newTodo = JSON.parse(localStorage.getItem("todoList"))[element.id.slice(element.id.length-1)-1];
newTodo.isChecked = element.checked.toString();
var todoList = JSON.parse(localStorage.getItem("todoList"));
todoList[element.id.slice(element.id.length-1)-1] = newTodo;
localStorage.setItem("todoList", JSON.stringify(todoList));
//apply css style
element.parentNode.style.textDecoration = "line-through";
}

Edit Text button not working

I'm trying to make an edit "button" that, when clicked, will launch a prompt window where you can enter new text that will replace the old text. The issue, I think, is that there is not an "edit button" in the html, it is created when an item is added to the to-do list. So I am having trouble targeting the text I want to replace.
Right now the "EditItem" function replaces the Edit button with the text I want, not the To-Do item. Any advice would really be appreciated!!
<html>
<head>
<title> To Do List</title>
<style>
body{
font: sans-serif;
color: #00b33c;
background-color: #ffffff;
}
p{
font: sans-serif;
width: auto;
}
ul {
list-style: none;
padding: 0;
margin: 0;
width: 500px;
}
li {
border: 2px solid #fff;
background: #e5ffff;
padding: 10px 10px;
color: #000000;
width: 500px;
}
li span{
padding-left: 10px;
padding-right: 200px;
}
.checked{
text-decoration: line-through;
font-weight: bold;
color: #ff0000;
}
li span2{
position: relative;
padding: 0 5px 0 5px;
margin: 10px;
font-size: 12px;
cursor: pointer;
border: 1px solid #000000;
background-color: #ffffff;
}
li span3{
font-size: 12px;
padding: 0 5px 0 5px;
position: relative;
cursor: pointer;
border: 1px solid #000000;
background-color: #ffffff;
}
}
</style>
</head>
<body>
<h1> To Do List</h1>
<p>
<input type="text" id="inItemText">
<button id="btnAdd">Add</button>
</p>
<ul id="todoList"></ul>
<script src="todolist.js"></script>
</body>
</html>
Javascript
//CheckBox Feature
function updateStatus() {
var cbId = this.id.replace("cb_", "");
var itemText = document.getElementById("item_" + cbId);
if (this.checked) {
itemText.className = "checked";
} else {
itemText.className = "";
}
}
//Delete Button
function deleteItem(){
this.parentNode.parentNode.removeChild(this.parentNode);
inItemText.focus();
inItemText.select();
}
//Edit Button
function editItem(e){
var newText = prompt("What would you like to change this to?");
if(newText !== null){
this.textContent = newText;
}
else{
alert("You must add something");
}
}
//Add new item to To-Do List
function addNewItem(list, itemText) {
totalItems++;
var listItem = document.createElement("li");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "cb_" + totalItems;
checkbox.onclick = updateStatus;
var span = document.createElement("span");
span.id = "item_" + totalItems;
span.textContent = itemText;
var spanDelete = document.createElement("span2");
spanDelete.setAttribute("id", listItem.id);
spanDelete.setAttribute("class", "delete");
spanDelete.textContent = "DELETE";
spanDelete.onclick = deleteItem;
var spanEdit = document.createElement("span3")
spanEdit.id = "editId_" + totalItems;
spanEdit.textContent = "EDIT";
spanEdit.onclick = editItem;
listItem.appendChild(checkbox);
listItem.appendChild(span);
listItem.appendChild(spanDelete);
listItem.appendChild(spanEdit);
list.appendChild(listItem);
}
//Add item to list with ENTER KEY
var totalItems = 0;
var inItemText = document.getElementById("inItemText");
inItemText.focus();
inItemText.onkeyup = function(event){
if(event.which === 13){
var itemText = inItemText.value;
if (!itemText || itemText === "" || itemText === " ") {
return false;
}
addNewItem(document.getElementById("todoList"), itemText);
inItemText.focus();
inItemText.select();
}
//Add item to To-Do List with "Add" Button
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = function() {
var itemText = inItemText.value;
if (!itemText || itemText === "" || itemText === " ") {
return false;
}
btnNew.onkeyup = function(event){
if(event.which == 13){
if (!itemText || itemText === "" || itemText === " ") {
return false;
}
}
}
addNewItem(document.getElementById("todoList"), itemText);
inItemText.focus();
inItemText.select();
}
}
Looking at this function in your codes
function editItem(e){
var newText = prompt("What would you like to change this to?");
if(newText !== null){
this.textContent = newText;
}
else{
alert("You must add something");
}
}
change this line this.textContent = newText; to
this.previousElementSibling.previousElementSibling.innerHTML = newText;
here is the snippet
//CheckBox Feature
function updateStatus() {
var cbId = this.id.replace("cb_", "");
var itemText = document.getElementById("item_" + cbId);
if (this.checked) {
itemText.className = "checked";
} else {
itemText.className = "";
}
}
//Delete Button
function deleteItem(){
this.parentNode.parentNode.removeChild(this.parentNode);
inItemText.focus();
inItemText.select();
}
//Edit Button
function editItem(e){
var newText = prompt("What would you like to change this to?");
if(newText !== null){
this.previousElementSibling.previousElementSibling.innerHTML = newText;
}
else{
alert("You must add something");
}
}
//Add new item to To-Do List
function addNewItem(list, itemText) {
totalItems++;
var listItem = document.createElement("li");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "cb_" + totalItems;
checkbox.onclick = updateStatus;
var span = document.createElement("span");
span.id = "item_" + totalItems;
span.textContent = itemText;
var spanDelete = document.createElement("span2");
spanDelete.setAttribute("id", listItem.id);
spanDelete.setAttribute("class", "delete");
spanDelete.textContent = "DELETE";
spanDelete.onclick = deleteItem;
var spanEdit = document.createElement("span3")
spanEdit.id = "editId_" + totalItems;
spanEdit.textContent = "EDIT";
spanEdit.onclick = editItem;
listItem.appendChild(checkbox);
listItem.appendChild(span);
listItem.appendChild(spanDelete);
listItem.appendChild(spanEdit);
list.appendChild(listItem);
}
//Add item to list with ENTER KEY
var totalItems = 0;
var inItemText = document.getElementById("inItemText");
inItemText.focus();
inItemText.onkeyup = function(event){
if(event.which === 13){
var itemText = inItemText.value;
if (!itemText || itemText === "" || itemText === " ") {
return false;
}
addNewItem(document.getElementById("todoList"), itemText);
inItemText.focus();
inItemText.select();
}
//Add item to To-Do List with "Add" Button
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = function() {
var itemText = inItemText.value;
if (!itemText || itemText === "" || itemText === " ") {
return false;
}
btnNew.onkeyup = function(event){
if(event.which == 13){
if (!itemText || itemText === "" || itemText === " ") {
return false;
}
}
}
addNewItem(document.getElementById("todoList"), itemText);
inItemText.focus();
inItemText.select();
}
}
body{
font: sans-serif;
color: #00b33c;
background-color: #ffffff;
}
p{
font: sans-serif;
width: auto;
}
ul {
list-style: none;
padding: 0;
margin: 0;
width: 500px;
}
li {
border: 2px solid #fff;
background: #e5ffff;
padding: 10px 10px;
color: #000000;
width: 500px;
}
li span{
padding-left: 10px;
padding-right: 200px;
}
.checked{
text-decoration: line-through;
font-weight: bold;
color: #ff0000;
}
li span2{
position: relative;
padding: 0 5px 0 5px;
margin: 10px;
font-size: 12px;
cursor: pointer;
border: 1px solid #000000;
background-color: #ffffff;
}
li span3{
font-size: 12px;
padding: 0 5px 0 5px;
position: relative;
cursor: pointer;
border: 1px solid #000000;
background-color: #ffffff;
}
}
<body>
<h1> To Do List</h1>
<p>
<input type="text" id="inItemText">
<button id="btnAdd">Add</button>
</p>
<ul id="todoList"></ul>
<script src="todolist.js"></script>
</body>

Categories