Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Book Constructor
- function Book(title, author, isbn) {
- this.title = title;
- this.author = author;
- this.isbn = isbn;
- }
- // UI Constructor
- function UI() {}
- // Add Book To List
- UI.prototype.addBookToList = function(book){
- const list = document.getElementById('book-list');
- // Create tr element
- const row = document.createElement('tr');
- // Insert cols
- row.innerHTML = `
- <td>${book.title}</td>
- <td>${book.author}</td>
- <td>${book.isbn}</td>
- <td><a href="#" class="delete">X<a></td>
- `;
- list.appendChild(row);
- }
- // Show Alert
- UI.prototype.showAlert = function(message, className){
- // create Div
- const div= document.createElement('div');
- // add Classes
- div.className = `alert ${className} `;
- // add text
- div.appendChild(document.createTextNode(message));
- // Get parent
- const container = document.querySelector('.container');
- // get the form
- const form = document.querySelector('#book-form');
- container.insertBefore(div, form);
- // Timeout after 3 sec
- setTimeout(()=>{
- document.querySelector('.alert').remove();
- }, 3000);
- }
- //Delete book
- UI.prototype.deleteBook = function(target){
- if(target.className === 'delete'){
- target.parentElement.parentElement.remove();
- }
- }
- // Clear Fields
- UI.prototype.clearFields = function() {
- document.getElementById('title').value = '';
- document.getElementById('author').value = '';
- document.getElementById('isbn').value = '';
- }
- // Event Listeners
- document.getElementById('book-form').addEventListener('submit', function(e){
- // Get form values
- const title = document.getElementById('title').value,
- author = document.getElementById('author').value,
- isbn = document.getElementById('isbn').value
- // Instantiate book
- const book = new Book(title, author, isbn);
- // Instantiate UI
- const ui = new UI();
- // Validate
- if(title === '' || author === '' || isbn === '') {
- // Error alert
- ui.showAlert('Please fill in all fields', 'error');
- } else {
- // Add book to list
- ui.addBookToList(book);
- // Show success
- ui.showAlert('Book Added!', 'success');
- // Clear fields
- ui.clearFields();
- }
- e.preventDefault();
- });
- // event litsiner for delete
- document.getElementById('book-list').addEventListener('click', (e) => {
- const ui = new UI();
- //Delete book
- ui.deleteBook(e.target);
- // show message
- ui.showAlert('book got Removed!', 'success')
- e.preventDefault();
- })
Add Comment
Please, Sign In to add comment