My program basically displays books and other information about it. It also should be able to delete said book from the library and also the array in which it is stored. This is where my problem lies, I can't seem to delete that exact book from the display and the array. I tried using array.pop() and deleteRow(), but they only delete from the bottom. Thanks in advance for the help.
let myLibrary = [];
function book(name, author, pages, hasRead) {
this.name = name;
this.author = author;
this.pages = pages;
this.read = hasRead;
}
const Book1 = new book('Harry Potter', 'J. K. Rowling', 322, 'Yes');
const Book2 = new book('Great Expectations', 'Charles Dickens', 234, 'Yes');
const Book3 = new book('To Kill a Mockingbird', 'Harper Lee', 312, 'No')
const Book4 = new book('The Great Gatsby', 'F Scott Fitzgerald', 421, 'Yes');
const Book5 = new book('Ulysses', 'James Joyce', 267, 'Yes');
myLibrary.push(Book1, Book2, Book3, Book4, Book5);
function tableHeader() {
var html = "<table id=myTable1>";
html += "<tr>";
html += "<th class=top1>" + 'BOOK NAME'+ "</th>";
html += "<th class=top2>" + 'AUTHOR' + "</th>";
html += "<th class=top3>" + 'PAGES' + "</th>";
html += "<th class=top4>" + 'READ?' + "</th>";
html += "</tr>";
html += "</table>";
document.getElementById("top").innerHTML = html
}
tableHeader();
function viewLibrary() {
var html = "<table id=myTable>";
for (i = 0; i < myLibrary.length; i++) {
html += "<tr>";
html += "<td>" + [i+1] + "</td>";
html += "<td class=box1>" + myLibrary[i].name + "</td>";
html += "<td class=box2>" + myLibrary[i].author + "</td>";
html += "<td class=box3>" + myLibrary[i].pages + "</td>";
html += "<td class=box4>" + myLibrary[i].read + "</td>";
html += "<td class=del>" + 'X' + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("box").innerHTML = html;
}
viewLibrary();
function deleteBook() {
var button = document.querySelectorAll('.del');
var table = document.getElementById('myTable');
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
button[i].addEventListener('click', function () {
table.deleteRow(this);
console.log(event);
myLibrary.pop();
})
}
}
deleteBook();
function addModal() {
var btn = document.getElementById("new-book");
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function () {
modal.style.display = "block";
}
span.onclick = function () {
modal.style.display = "none";
}
}
addModal();
function addBookToLibrary() {
let name = document.getElementById('name').value;
let author = document.getElementById('author').value;
let pages = document.getElementById('pages').value;
let read = document.getElementById('dropdown').value;
var submit = document.getElementById("submit");
var modal = document.getElementById("myModal");
if (name === '' || author === '' || pages === '' || read === '') {
alert("Fill out all values.")
return false;
} else {
submit.onclick = function () {
modal.style.display = "none";
}
const NewBook = new book(name, author, pages, read);
myLibrary.push(NewBook);
console.log(NewBook);
viewLibrary();
document.getElementById('name').value = '';
document.getElementById('author').value = '';
document.getElementById('pages').value = '';
document.getElementById('dropdown').value = '';
deleteBook();
}
}
let x = document.querySelectorAll('button');
x.forEach(button => {
button.addEventListener('click', () => {
let selection = button.innerHTML;
switch (selection) {
case "Submit":
addBookToLibrary();
break;
}
})
})
body {
background-color: #edc4b3;
}
/* The Modal (background) */
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
/* Modal Content/Box */
.modal-content {
background-color: #eddcd2;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 40%;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
table {
margin-left: 14.5%;
margin-top: 5%;
width: 70%;
background-color: #edddd4;
border: 5px solid #8d99ae;
border-collapse: collapse;
margin-top: 2%;
}
#top {
color: #9d6b53;
}
#box {
margin-top: -1.5%;
}
.line {
color: #774936;
}
td {
padding-bottom: 10px;
padding-top: 10px;
padding-left: 10px;
}
h1 {
text-align: center;
text-transform: uppercase;
font-family: 'Notable', sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
#new-book {
margin-left: 79%;
background-color: #888;
cursor: pointer;
margin-top: 2%;
padding: 5px 5px;
font-weight: bold;
}
/*tr:first-child { font-weight: bold }*/
#name, #author, #pages {
width: 60%;
border: 0;
border-bottom: 1px solid black;
font-size: 1rem;
color: black;
background-color: #eddcd2;
font-family: 'Times New Roman', Times, serif;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 2px;
padding-right: 2px;
}
td {
font-family: 'Source Code Pro', monospace;
}
#author {
width: 58.5%;
}
#pages {
width: 61.3%;
}
#dropdown {
width: 28%;
background-color: #edddd4;
font-size: 17px;
cursor: pointer;
box-sizing: border-box;
margin: 0;
border: 1px solid black;
padding-top: 5px;
padding-bottom: 5px;
}
#submit {
background-color: black;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
width: 30%;
margin-left: 35%;
}
input:focus,
select:focus,
textarea:focus,
button:focus {
outline: none;
}
.del {
color: red;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Library</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<button id='new-book'>Add Book</button>
<section id="top"></section>
<section id="box"></section>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<h2>Add a new book</h2>
<label for="name">Name of the Book:</label>
<input type="text" id="name" name="fname" required><br><br>
<label for="author">Name of the Author:</label>
<input type="text" id="author" name="lname" required><br><br>
<label for="pages">Number of Pages:</label>
<input type="number" id="pages" name="pname" required><br><br>
<p>Have you read this book?</p>
<select id="dropdown" required>
<option value="" disabled selected>Select your option</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select><br><br>
<button id="submit">Submit</button>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
I would suggest a different approach. Instead of creating your new elements through string concatenation and .innerHTML (which has performance and security implications), use the DOM API to create your new elements and then just attach an event handler to the dynamically created cells that contain the X.
See additional comments inline below:
let headers = ["name", "author", "pages", "read"];
// Get your DOM references just once, not every time
// your event handlers execute and make sure to always
// reference the DOM element, rather than a property
// of the DOM element. That way, if you ever decide
// that you need a different property value, you won't
// have to scan the DOM for the element reference again.
let box = document.getElementById("box");
var btn = document.getElementById("new-book");
var modal = document.getElementById("myModal");
let closeModal = document.querySelector("span.close");
let name = document.getElementById('name');
let author = document.getElementById('author');
let pages = document.getElementById('pages');
let read = document.getElementById('dropdown');
var submit = document.getElementById("submit");
var modal = document.getElementById("myModal");
// DO NOT USE GETELEMENTSBYCLASSNAME and especially
// pass an idex to the first element within it:
// var span = document.getElementsByClassName("close")[0];
// Read this for details: https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474
// Instead, use .querySelector()
var span = document.querySelector(".close");
// Bind the "buttons" that show/hide the modal
// to a common function that does that.
btn.addEventListener('click', showHideModal);
closeModal.addEventListener('click', showHideModal);
function showHideModal(){
// No need for if/then. Just toggle the use of
// the .hidden CSS class
modal.classList.toggle("hidden");
}
submit.addEventListener('click', addBookToLibrary);
function book(name, author, pages, hasRead) {
this.name = name;
this.author = author;
this.pages = pages;
this.read = hasRead;
}
// No need to create variables to store new book references,
// and then push them into the Array. Just put the new books
// directly into the new Array.
let myLibrary = [
new book('Harry Potter', 'J. K. Rowling', 322, 'Yes'),
new book('Great Expectations', 'Charles Dickens', 234, 'Yes'),
new book('To Kill a Mockingbird', 'Harper Lee', 312, 'No'),
new book('The Great Gatsby', 'F Scott Fitzgerald', 421, 'Yes') ,
new book('Ulysses', 'James Joyce', 267, 'Yes')
];
function makeLibrary() {
// Get rid of the prior table (if exists)
if(document.getElementById("myTable")){
document.getElementById("myTable").remove();
}
// Instead of creating concatenated strings of HTML, which gets
// messy and hard to maintain, create DOM objects and set their
// propeties.
let tbl = document.createElement("table");
tbl.id = "myTable";
for (i = 0; i < myLibrary.length; i++) {
let row = document.createElement("tr");
let numCell = document.createElement("td");
numCell.textContent = i + 1;
row.appendChild(numCell);
// Loop over the headers array to build the row cells
headers.forEach(function(header, index){
let cell = document.createElement("td");
cell.textContent = myLibrary[i][header];
cell.classList.add("box" + (index + 1));
row.appendChild(cell); // Add the cell to the row
});
let delCell = document.createElement("td");
delCell.textContent = "X";
delCell.classList.add("del");
// Because the elements are now being created as elements
// and not strings, you can set up even binding on them.
delCell.addEventListener("click", function(){
myLibrary.splice(i, 1); // Remove book from library
this.closest("tr").remove(); // Remove row
});
row.appendChild(delCell); // Add cell to row
tbl.appendChild(row); // Add row to table
box.appendChild(tbl); // Add table to section
}
}
makeLibrary();
function addBookToLibrary() {
if (name.value === '' || author.value === '' || pages.value === '' || read.value === '') {
alert("Fill out all values.")
return false;
} else {
myLibrary.push(new book(name.value, author.value, pages.value, read.value));
makeLibrary();
name.value = '';
author.value = '';
pages.value = '';
dropdown.value = '';
showHideModal();
}
}
body {
background-color: #edc4b3;
}
/* Added classes */
h1.addBook { font-size: 1em; }
.hidden { display:none; }
/* The Modal (background) */
.modal {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
/* Modal Content/Box */
.modal-content {
background-color: #eddcd2;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 40%;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
table {
margin-left: 14.5%;
margin-top: 5%;
width: 70%;
background-color: #edddd4;
border: 5px solid #8d99ae;
border-collapse: collapse;
margin-top: 2%;
}
#top {
color: #9d6b53;
}
#box {
margin-top: -1.5%;
}
.line {
color: #774936;
}
td {
padding-bottom: 10px;
padding-top: 10px;
padding-left: 10px;
}
h1 {
text-align: center;
text-transform: uppercase;
font-family: 'Notable', sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
#new-book {
margin-left: 79%;
background-color: #888;
cursor: pointer;
margin-top: 2%;
padding: 5px 5px;
font-weight: bold;
}
/*tr:first-child { font-weight: bold }*/
#name, #author, #pages {
width: 60%;
border: 0;
border-bottom: 1px solid black;
font-size: 1rem;
color: black;
background-color: #eddcd2;
font-family: 'Times New Roman', Times, serif;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 2px;
padding-right: 2px;
}
td {
font-family: 'Source Code Pro', monospace;
}
#author {
width: 58.5%;
}
#pages {
width: 61.3%;
}
#dropdown {
width: 28%;
background-color: #edddd4;
font-size: 17px;
cursor: pointer;
box-sizing: border-box;
margin: 0;
border: 1px solid black;
padding-top: 5px;
padding-bottom: 5px;
}
#submit {
background-color: black;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
width: 30%;
margin-left: 35%;
}
input:focus,
select:focus,
textarea:focus,
button:focus {
outline: none;
}
.del {
color: red;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Library</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<button id='new-book'>Add Book</button>
<section id="top">
<!-- If you have static bits of HTML, don't create them
dynamically in JavaScript, go ahead and hard-code them
into the HTML. This will reduce the amount of JavaScript
and improve the speed of the page load. -->
<table id="myTable1">
<tr>
<th class="top1">BOOK NAME</th>
<th class=top2>AUTHOR</th>
<th class=top3>PAGES</th>
<th class=top4>READ?</th>
</tr>
</table>
</section>
<section id="box"></section>
<div id="myModal" class="modal hidden">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<!-- You can't have an H2 if it's not a child of an H1.
Don't choose a heading because of how it looks, pick
it because it represents the right heading level and
then style it with CSS. -->
<h1 class="addBook">Add a new book</h1>
<label for="name">Name of the Book:</label>
<input type="text" id="name" name="fname" required><br><br>
<label for="author">Name of the Author:</label>
<input type="text" id="author" name="lname" required><br><br>
<label for="pages">Number of Pages:</label>
<input type="number" id="pages" name="pname" required><br><br>
<p>Have you read this book?</p>
<select id="dropdown" required>
<option value="" disabled selected>Select your option</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select><br><br>
<button id="submit">Submit</button>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
function deleteBook() {
var button = document.querySelectorAll('.del');
var table = document.getElementById('myTable');
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
button[i].addEventListener('click', function () {
table.deleteRow(i);
// I think pop will delete only the last element.
myLibrary.splice(i, 1);
})
}
}
this in table.deleteRow(this) refers to a HTMLTableCellElement.
According to this doc : https://www.w3schools.com/jsreF/met_table_deleterow.asp
You'll need to pass an index instead.
Edit :
What about adding a data-row attribute to your rows where you put the index, and then getting this index by using element.dataset.row
E.G :
var html = "<table id=myTable1>";
html += "<tr data-row=" + $yourIndex + ">";
html += "<th class=top1>" + 'BOOK NAME'+ "</th>";
html += "<th class=top2>" + 'AUTHOR' + "</th>";
html += "<th class=top3>" + 'PAGES' + "</th>";
html += "<th class=top4>" + 'READ?' + "</th>";
html += "</tr>";
html += "</table>";
Use Splice to remove the element from the array. Use this link for your reference.
your way of explanation is a little bit vague to understand.
Related
Still learning so bear with me.
I am building a test project where I have a simple input that I show it on the same page as a list. (grocery or to do list project)
So when a user hits the ok button I create a new li inside a ul element. That goes ok.
I want to implement the following though: When the user clicks on the new element (li) I want to change the text decoration to line-though and show a trash icon where it will remove this li element by clicking on it.
I have managed to do that. The problem is that when the user clicks again on the new element (li) I get a second trash image.
I want help to succeed in this: when a user clicks on the element while it has text-decoration = line-through to hide or remove the trash icon and make text-decoration none again.
Here is a code pen for this project to check out. Just insert a new item on the list and then click twice on it: https://codepen.io/dourvas-ioannis/pen/MWVBjNZ
This is the function I am using when the user hits the add button to add a list item:
function addToList(){
let newListItem = document.createElement('li');
newListItem.textContent = userInput.value;
list.appendChild(newListItem);
userInput.value = "";
newListItem.addEventListener('click', function(){
this.style.textDecoration = 'line-through';
let itemButton = document.createElement('a');
itemButton.setAttribute('href', '#');
itemButton.classList.add('trash-image');
itemButton.innerHTML = '<i class="material-icons">delete</i><a/>';
itemButton.addEventListener("click", deleteOneItem);
this.appendChild(itemButton);
});
}
function deleteOneItem(){
this.parentNode.remove();
}
//select from DOM
let allItems = document.querySelector('#allItems');
let button = document.querySelector('#add-button');
let userInput = document.querySelector('#item');
let list = document.querySelector('#list');
let clear = document.querySelector('#clear-button');
//add event listener
button.addEventListener('click', addToList);
clear.addEventListener('click', clearAll);
//functions
function addToList() {
let newListItem = document.createElement('li');
newListItem.textContent = userInput.value;
list.appendChild(newListItem);
userInput.value = "";
newListItem.addEventListener('click', function() {
this.style.textDecoration = 'line-through';
let itemButton = document.createElement('a');
itemButton.setAttribute('href', '#');
itemButton.classList.add('trash-image');
itemButton.innerHTML = '<i class="material-icons">delete</i><a/>';
itemButton.addEventListener("click", deleteOneItem);
this.appendChild(itemButton);
});
}
function deleteOneItem() {
this.parentNode.remove();
}
function clearAll() {
list.innerHTML = "";
}
body {
font-size: 10px;
font-family: Arial, Helvetica, sans-serif;
margin: 0;
background-color: antiquewhite;
}
#container {
width: 80%;
margin: auto;
padding-top: 10px;
background-color: rgb(200, 225, 225);
color: rgb(52, 48, 48);
border-radius: 10px;
}
p {
font-size: 20px;
text-align: center;
padding: 30px, 0px, 5px, 0px;
}
#formdiv {
text-align: center;
}
#item {
size: 100px;
}
#clear {
margin-top: 60px;
text-align: center;
}
li {
list-style-type: none;
font-size: 3.2em;
padding: 0.5em;
margin: 1em;
background-color: lightyellow;
border-radius: 5px;
border: 1px solid grey;
}
.trash-image {
float: right;
margin: -2px 3px 3px 3px;
vertical-align: middle;
height: 4px;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<body>
<br> <br> <br>
<div id='container'>
<p>My list</p>
<br>
<div id="formdiv">
<label for="item">add this.. </label><br>
<input type="text" name="item" id="item">
<button id="add-button"> add </button>
</div>
<div id="allItems">
<ul id="list">
</ul>
</div>
<div id="clear">
<button id="clear-button"> Clear List </button><br> <br> <br>
</div>
</div>
Here's a quick example implementation of the approach I mentioned in the comments. I've just hacked it together quickly, so there's a small difference for the bin.
I've used an img (without a src) instead of a 'character' from the
font. I've styled the img to be 16x16 for the same reason. It also
makes it visible instead of being 0x0 pixels. I also set the cursor.
"use strict";
window.addEventListener('load', onLoad, false);
function onLoad(evt) {
document.querySelector('button').addEventListener('click', onAddBtnClicked, false);
}
function onAddBtnClicked(evt) {
let userText = document.querySelector('input').value;
let newLi = document.createElement('li');
newLi.textContent = userText;
newLi.addEventListener('click', onIncompleteItemClicked, false);
document.querySelector('ul').appendChild(newLi);
}
function onIncompleteItemClicked(evt) {
let clickedLi = this;
clickedLi.classList.toggle('itemComplete');
let binImg = document.createElement('img');
binImg.addEventListener('click', onBinIconClicked, false);
clickedLi.appendChild(binImg);
clickedLi.removeEventListener('click', onIncompleteItemClicked, false);
clickedLi.addEventListener('click', onCompletedItemClicked, false);
}
function onCompletedItemClicked(evt) {
let clickedLi = this;
clickedLi.classList.toggle('itemComplete');
let binImg = clickedLi.querySelector('img');
clickedLi.removeChild(binImg);
clickedLi.removeEventListener('click', onCompletedItemClicked, false);
clickedLi.addEventListener('click', onIncompleteItemClicked, false);
}
function onBinIconClicked(evt) {
let clickedBin = this;
let containingLi = clickedBin.parentNode;
containingLi.remove();
}
.itemComplete {
text-decoration: line-through;
}
li>img {
cursor: pointer;
width: 16px;
height: 16px;
}
<input value='blah-blah'></input><button>Add</button>
<ul></ul>
Add a variable indicating that the icon has been already added.
Check if icon is added on click
If yes - skip
If not - set icon
//select from DOM
let allItems = document.querySelector('#allItems');
let button = document.querySelector('#add-button');
let userInput = document.querySelector('#item');
let list = document.querySelector('#list');
let clear = document.querySelector('#clear-button');
//add event listener
button.addEventListener('click', addToList);
clear.addEventListener('click', clearAll);
//functions
function addToList() {
let newListItem = document.createElement('li');
newListItem.textContent = userInput.value;
list.appendChild(newListItem);
userInput.value = "";
// declare boolean variable
let hasTrashIcon = false
newListItem.addEventListener('click', function() {
// if has thrash icon skip
if (hasTrashIcon) return
// set has trash icon
hasTrashIcon = true
this.style.textDecoration = 'line-through';
let itemButton = document.createElement('a');
itemButton.setAttribute('href', '#');
itemButton.classList.add('trash-image');
itemButton.innerHTML = '<i class="material-icons">delete</i><a/>';
itemButton.addEventListener("click", deleteOneItem);
this.appendChild(itemButton);
});
}
function deleteOneItem() {
this.parentNode.remove();
}
function clearAll() {
list.innerHTML = "";
}
body {
font-size: 10px;
font-family: Arial, Helvetica, sans-serif;
margin: 0;
background-color: antiquewhite;
}
#container {
width: 80%;
margin: auto;
padding-top: 10px;
background-color: rgb(200, 225, 225);
color: rgb(52, 48, 48);
border-radius: 10px;
}
p {
font-size: 20px;
text-align: center;
padding: 30px, 0px, 5px, 0px;
}
#formdiv {
text-align: center;
}
#item {
size: 100px;
}
#clear {
margin-top: 60px;
text-align: center;
}
li {
list-style-type: none;
font-size: 3.2em;
padding: 0.5em;
margin: 1em;
background-color: lightyellow;
border-radius: 5px;
border: 1px solid grey;
}
.trash-image {
float: right;
margin: -2px 3px 3px 3px;
vertical-align: middle;
height: 4px;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<body>
<br> <br> <br>
<div id='container'>
<p>My list</p>
<br>
<div id="formdiv">
<label for="item">add this.. </label><br>
<input type="text" name="item" id="item">
<button id="add-button"> add </button>
</div>
<div id="allItems">
<ul id="list">
</ul>
</div>
<div id="clear">
<button id="clear-button"> Clear List </button><br> <br> <br>
</div>
</div>
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>
const addBtn = document.querySelector(".add");
const modal = document.querySelector(".modal__container");
const library = document.querySelector(".library__container");
const submitBook = document.querySelector(".add__book");
const deleteBtn = document.querySelector(".fas fa-trash-alt");
//Modal inputs
const modalTitle = document.querySelector("#title");
const modalAuthor = document.querySelector("#author");
const modalPages = document.querySelector("#pages");
const isRead = document.querySelector("#read-status");
//Toggle Modal
const hideModal = () => {
modal.style.display = "none";
};
const showModal = () => {
modal.style.display = "block";
const cancel = document.querySelector(".cancel");
cancel.addEventListener("click", (e) => {
e.preventDefault();
hideModal();
});
};
addBtn.addEventListener("click", showModal);
let myLibrary = [];
let index = 0;
function Book(title, author, pages, read) {
this.title = title,
this.author = author,
this.pages = pages,
this.read = read
}
submitBook.addEventListener("click", addBookToLibrary);
function addBookToLibrary(e) {
e.preventDefault();
let bookTitle = modalTitle.value;
let bookAuthor = modalAuthor.value;
let bookPages = modalPages.value;
let bookStatus = isRead.checked;
//Display error message if inputs are empty
if (bookTitle === "" || bookAuthor === "" || bookPages === "") {
const errorMessage = document.querySelector(".error__message--container");
hideModal();
errorMessage.style.display = "block";
const errorBtn = document.querySelector(".error-btn");
errorBtn.addEventListener("click", () => {
errorMessage.style.display = "none";
showModal();
})
} else {
let book = new Book(bookTitle, bookAuthor, bookPages, bookStatus);
myLibrary.push(book);
hideModal();
render();
}
}
function render() {
library.innerHTML = "";
for (let i = 0; i < myLibrary.length; i++) {
library.innerHTML +=
'<div class="book__container">' +
'<div class="book">' +
'<div class="title__content">' +
'<span class="main">Title : </span><span class="book__title">' +` ${myLibrary[i].title}`+'</span>' +
'</div>' +
'<div class="author__content">' +
'<span class="main">Author : </span><span class="book__author">'+` ${myLibrary[i].author}`+'</span>' +
'</div>' +
'<div class="pages__content">' +
'<span class="main">Pages : </span><span class="book__pages">'+` ${myLibrary[i].pages}`+'</span>' +
'</div>' +
'<div class="book__read-elements">' +
'<span class="book__read">I read it</span>' +
'<i class="fas fa-check"></i>' +
'<a href="#"><i class="fas fa-times"></i>' +
'<i class="fas fa-trash-alt"></i>' +
'</div>' +
'</div>' +
'</div>'
readStatus(myLibrary[i].checked)
}
modalTitle.value = "";
modalAuthor.value = "";
modalPages.value = "";
isRead.checked = false;
}
function readStatus(bookStatus) {
const bookStatusContainer = document.querySelector(".book__read");
if (bookStatus) {
bookStatusContainer.classList.add("yes");
bookStatusContainer.textContent = "I read it";
bookStatusContainer.style.color = "rgb(110, 176, 120)";
} else {
bookStatusContainer.classList.add("no");
bookStatusContainer.textContent = "I have not read it";
bookStatusContainer.style.color = "rgb(194, 89, 89)";
}
}
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#300;400;600&display=swap');
:root {
--light-gray: #dededef3;
--title-color: #333756;
--main-color: #c6c6c6f3;
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font-family: 'Poppins', sans-serif;
background-color: var(--light-gray);
}
header {
text-align: center;
padding-top: 4rem;
color: var(--title-color);
text-transform: uppercase;
letter-spacing: 4px;
}
button {
margin: 1rem;
padding: 0.8rem 2rem;
font-size: 14px;
border-radius: 25px;
background: white;
color: #333756;
font-weight: 600;
border: none;
cursor: pointer;
transition: 0.6s all ease;
}
:focus {
/*outline: 1px solid white;*/
}
button:hover {
background: var(--title-color);
color: white;
}
.add__book:hover,
.cancel:hover {
background: var(--main-color);
color: var(--title-color)
}
.all,
.books__read,
.books__not-read {
border-radius: 0;
text-transform: uppercase;
letter-spacing: 0.1rem;
background: var(--light-gray);
border-bottom: 4px solid var(--title-color)
}
.library__container {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.book__container {
display: flex;
margin: 2rem 2rem;
}
.modal__container {
display: none;
position: fixed;
z-index: 4;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
padding-top: 0px;
}
.book,
.modal {
padding: 2rem 2rem;
border-radius: 15px;
background: #333756;
line-height: 3rem;
}
.modal {
position: relative;
width: 50%;
margin: 0 auto;
margin-top: 8rem;
}
.modal__content {
display: flex;
flex-direction: column;
}
label {
color: white;
margin-right: 1rem;
}
input {
padding: 0.5rem;
font-size: 14px;
}
.book__read-elements {
display: flex;
justify-content: space-between;
}
.main,
i {
color: white;
pointer-events: none;
margin: 0.5rem;
}
.book__title,
.book__author,
.book__pages,
.book__read {
color: var(--main-color)
}
.error__message--container {
display: none;
position: fixed;
z-index: 4;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
.error__message--modal {
position: relative;
margin: 0 auto;
margin-top: 10rem;
width:40%;
}
.error {
display: flex;
flex-direction: column;
align-items: center;
color: rgb(101, 3, 3);
font-size: 20px;
font-weight: bold;
background: rgb(189, 96, 96);
padding: 3rem 5rem;
border-radius: 10px;
}
.error-btn {
color: rgb(101, 3, 3);
font-weight: bold;
}
.error-btn:hover {
color: white;
background: rgb(101, 3, 3);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css" integrity="sha256-2XFplPlrFClt0bIdPgpz8H7ojnk10H69xRqd9+uTShA=" crossorigin="anonymous" />
<link rel="stylesheet" href="styles.css">
<title>Library</title>
</head>
<body>
<header>
<h1>My Library</h1>
<button class="add">Add New Book</button>
<div class="buttons">
<button class="all">View All</button>
<button class="books__read">Read</button>
<button class="books__not-read">Not Read</button>
</div>
</header>
<div class="error__message--container">
<div class="error__message--modal">
<div class="error">
<p>Complete the form!</p>
<button class ="error-btn">Ok</button>
</div>
</div>
</div>
<!--Modal-->
<form class="modal__container">
<div class="modal">
<div class="modal__content">
<label for="">Title:</label>
<input type="text" id="title">
</div>
<div class="modal__content">
<label for="">Author:</label>
<input type="text" id="author">
</div>
<div class="modal__content">
<label for="">Pages:</label>
<input type="number" id="pages">
</div>
<div>
<label for="read-status">Check the box if you've read this book</label>
<input type="checkbox" id="read-status" value ="check">
</div>
<button class="add__book">Add</button>
<button class="cancel">Cancel</button>
</div>
</form>
<!--End of Modal-->
<div class="library__container"></div>
<script src="script.js"></script>
</body>
</html>
I'm new to OOP and I'm struggling.
I'm building a library where you can add a book with the title, author nr of pages and if you've read it or not. When I add the first book if I check the box it displays that to book is not read(which is false). When I add a new book the read functionality is not applied to that book at all. I have no idea how to fix it
In this function you are checking the status if isRead which is incorrect.
Do this
Call the readStatus function inside the for loop
Pass the current parameter readStatus(myLibrary[i].checked)
Modify readStatus as shown below
function readStatus(status) {
const bookReadStatus = document.querySelector(".book__read");
if (status) {
bookReadStatus.classList.add("yes");
bookReadStatus.textContent = "I read it";
bookReadStatus.style.color = "rgb(110, 176, 120)";
} else {
bookReadStatus.classList.add("no");
bookReadStatus.textContent = "I have not read it";
bookReadStatus.style.color = "rgb(194, 89, 89)";
}
}
I need help to write a code that creates an input element and then get the user's input by click on button.
Do I need 2 functions? one for creating the elements and other for the Game(?).
the main problem for me is to get the text value after creating input.
I created an element, but I dont know how I can "pull" out the value of the user's text.
let btGame = document.querySelector("#game");
btGame.addEventListener('click', startGame)
function startGame() {
createGame();
}
function createGame(textInputValue) {
let gameBox = document.querySelector(".gameBox");
let textInput = document.createElement("input");
let btGuess = document.createElement("input");
textInput.type = "text";
textInput.id = "inputof";
textInput.setAttribute('placeholder', 'guess a number between 1-6');
btGuess.setAttribute('type', 'button');
btGuess.setAttribute('class', 'go');
btGuess.value = "guess";
gameBox.appendChild(textInput);
gameBox.appendChild(btGuess);
}
* {
box-sizing: border-box;
}
.gameBox {
width: 30%;
text-align: center;
border: 2px dotted #ffc452;
}
.gameTitle {
font-family: cursive;
font-style: oblique;
cursor: pointer;
}
.gameTitle:hover {
transition: 2s;
font-size: 35px;
color: gold;
}
#inputof {
position: relative;
width: 100%;
margin-top: 50px;
margin-bottom: 50px;
text-align: center;
}
<body>
<div class="gameBox">
<h1 class="gameTitle">want to play a game?</h1>
<input type="button" id="game" value="click here to start">
</div>
</body>
Add an event listener to the created btGuess when createGame is called:
let btGame = document.querySelector("#game");
btGame.addEventListener('click', startGame)
function startGame() {
createGame();
}
function createGame(textInputValue) {
let gameBox = document.querySelector(".gameBox");
let textInput = document.createElement("input");
let btGuess = document.createElement("input");
textInput.type = "text";
textInput.id = "inputof";
textInput.setAttribute('placeholder', 'guess a number between 1-6');
btGuess.setAttribute('type', 'button');
btGuess.setAttribute('class', 'go');
btGuess.value = "guess";
gameBox.appendChild(textInput);
gameBox.appendChild(btGuess);
btGuess.addEventListener('click', () => {
console.log('You inputted:', textInput.value);
});
}
* {
box-sizing: border-box;
}
.gameBox {
width: 30%;
text-align: center;
border: 2px dotted #ffc452;
}
.gameTitle {
font-family: cursive;
font-style: oblique;
cursor: pointer;
}
.gameTitle:hover {
transition: 2s;
font-size: 35px;
color: gold;
}
#inputof {
position: relative;
width: 100%;
margin-top: 50px;
margin-bottom: 50px;
text-align: center;
}
<body>
<div class="gameBox">
<h1 class="gameTitle">want to play a game?</h1>
<input type="button" id="game" value="click here to start">
</div>
</body>
as CertainPerformance said, add an event listener to btGuess when createGame is called. I used a separate function to manage the game logic and inserted guessValue variable containing the value to guess when you click the guess button
let btGame = document.querySelector("#game");
btGame.addEventListener('click' , startGame);
var guessValue;
function startGame()
{
createGame();
guessValue = Math.floor(Math.random() * 6) + 1;
console.log(guessValue);
}
function createGame(textInputValue)
{
let gameBox = document.querySelector(".gameBox");
let textInput = document.createElement("input");
let btGuess = document.createElement("input");
textInput.type = "text";
textInput.id = "inputof";
textInput.setAttribute('placeholder' , 'guess a number between 1-6');
btGuess.setAttribute('type' , 'button');
btGuess.setAttribute('class' , 'go');
btGuess.value = "guess";
btGuess.addEventListener('click',() => play())
gameBox.appendChild(textInput);
gameBox.appendChild(btGuess);
}
function play(){
let input = document.getElementById('inputof').value;
console.log(input);
if(input == guessValue){
alert('You Won')
}
else {
alert('Game over')
}
}
*
{
box-sizing: border-box;
}
.gameBox
{
width: 30%;
text-align: center;
border: 2px dotted #ffc452;
}
.gameTitle
{
font-family: cursive;
font-style: oblique;
cursor: pointer;
}
.gameTitle:hover
{
transition: 2s;
font-size: 35px;
color: gold;
}
#inputof
{
position: relative;
width: 100%;
margin-top: 50px;
margin-bottom: 50px;
text-align: center;
}
<body>
<div class="gameBox">
<h1 class="gameTitle">want to play a game?</h1>
<input type="button" id="game" value="click here to start">
</div>
</body>
In the above image the delete button need to align properly. in my code it get align based on file name length.
<script>
var filelist = new Array();
updateList = function () {
var input = document.getElementById('fileUploader');
var output = document.getElementById('divFiles');
var HTML = "<table>";
for (var i = 0; i < input.files.length; ++i) {
filelist[i]=input.files.item(i).name;
HTML += "<tr><td>" + filelist[i] + "</td><td> <button ></button></td></tr>";
}
HTML += "</table>";
output.innerHTML += HTML;
}
</script>
Please try this.
table {
border-collapse: separate;
border-spacing: 0 3px;
width: 600px;
}
Try this
table
{
table-layout: fixed;
width: 300px;
}
td
{
border: 1px solid green;
word-wrap:break-word;
}
try jsfiddle
<style>
table {
border-collapse: separate;
border-spacing: 0 2px;
width: 600px;
table-layout: fixed;
}
tr:nth-child(1n) {
border: 2px solid;
background-color: #eceff1;
color: Black;
}
tr:nth-child(2n) {
border: 2px solid;
color: Black;
}
td {
padding-top: .5em;
padding-left: .5em;
padding-right: .5em;
padding-bottom: .5em;
}
input[type="file"] {
display: none;
}
.label1 {
padding: 3px;
background: #fff;
display: table;
color:black;
}
button {
background-image: url('../../Images/delete.ico');
background-size: cover;
padding-right:0px;
background-color: Transparent;
cursor: pointer;
border: none;
width: 30px;
height: 30px;
}
</style>
<script>
$(document).ready(function () {
$(document).on('click', "button", function (e) {
$(this).closest('tr').remove();
});
});
</script>
<script>
var filelist = new Array();
updateList = function () {
var input = document.getElementById('fileUploader');
var output = document.getElementById('divFiles');
var HTML = "<table>";
for (var i = 0; i < input.files.length; ++i) {
filelist[i]=input.files.item(i).name;
HTML += "<tr><td>" + filelist[i] + "</td><td><button ></button></td></tr>";
}
HTML += "</table>";
output.innerHTML += HTML;
}
</script>
In the above script the delete button is showing in fixed order but i want the file name to be aligned at left and delete button need to at right side corner.