JSFiddle - React, Tailwind, and code Playground
by chi1010860
HTML
<div class="container">
<h1>Library</h1>
<button type="button" onclick="addBookToLibrary();" id="addButton">Add A Book</button>
<div class="formContainer">
<form id="info">
<input type="text" placeholder="Title" id="title">
<input type="text" placeholder="Author" id="author">
<input type="number" placeholder="#Pages" min="0" max="5000" id="number">
<label for="read">Read?</label>
<input type="checkbox" id="read" value="Read">
</form>
</div>
</div>
<hr>
<div class="bookContainer">
<div class="wrapper">
<h2>Title</h2>
<h2>Author</h2>
<h2>Pages</h2>
<h2>Read</h2>
</div>
<div class="books">
<div class="book">
<p class="item">The Hobbit</p>
<p class="item">by J.R.R. Tolkien</p>
<p class="item">295 pages</p>
<p class="item">Read</p>
</div>
</div>
</div>
CSS
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
#addButton {
margin-bottom: 1em;
}
.container {
text-align: center;
}
.container h1 {
margin-top: 0.5em;
margin-bottom: 0.5em;
}
hr {
margin-top: 2em;
margin-bottom: 2em;
}
.bookContainer{
width: 90%;
border: 2px solid black;
margin: auto;
}
.wrapper {
display: flex;
justify-content: space-around;
}
.book {
display: flex;
justify-content: space-around;
margin-top: 1em;
}
.item {
flex: 1;
text-align: center;
}
#number {
width: 8%;
}
JavaScript
let myLibrary = [
{
title: 'The Hobbit',
author: 'by J.R.R. Tolkien',
pages: '295 pages',
read: 'Read'
}
];
function book(title, author, pages, read) {
this.title = title
this.author = author
this.pages = pages
this.read = read
this.info = function () {
console.log(title, author, pages, read);
}
}
function addBookToLibrary() {
// get value from the input text
let title = document.querySelector('#title').value;
let author = document.querySelector('#author').value;
let pages = document.querySelector('#number').value;
let read = document.querySelector('#read').checked ? document.querySelector('#read').value : '';
// create a book
let b1 = new book(title, author, pages, read);
// append data to the array myLibrary
myLibrary.push(b1);
// invoke render function
render();
}
function render() {
//display array data
let pval = '';
for (i = 0; i < myLibrary.length; i++) {
pval += '<div class="book">';
pval += '<p class="item">' + myLibrary[i].title + '</p>';
pval += '<p class="item">' + myLibrary[i].author + '</p>';
pval += '<p class="item">' + myLibrary[i].pages + '</p>';
pval += '<p class="item">' + myLibrary[i].read + '</p>';
pval += '</div>'
}
document.querySelector('.books').innerHTML = pval;
}