Home > Net >  Save the input from the user make even after reload/refresh
Save the input from the user make even after reload/refresh

Time:07-16

I wanted to to add a function that every time the user refresh, reload or even close the page, the user to able to see the data (added books) whatever the user had entered previously or choose in the .

Also when the user make an update and refresh they show be able to see the change.

javascript file

console.log('This is ES6 version of project 2');

class Book {

    constructor(name, author, type) {
        this.name = name;
        this.author = author;
        this.type = type;
    }
}

class Display {
    add(book) {
        console.log('Adding to UI');
        let tableBody = document.getElementById('tableBody')
        let uiString = `<tr>
                            <td>${book.name}</td>
                            <td>${book.author}</td>
                            <td>${book.type}</td>
                        </tr>`;
        tableBody.innerHTML  = uiString;

    }

    clear() {
        let libraryForm = document.getElementById('libraryForm');
        libraryForm.reset();
    }

    validate(book) {
        if (book.name.length < 2 || book.author.length < 2) {
            return false;
        }
        else {
            return true;
        }
    }

    show (type, displayMessage) {
        let message = document.getElementById('message');
        let boldText;
        if (type === 'success'){
            boldText = 'Success';
        }
        else{
            boldText = 'Error!';
        }
        message.innerHTML = `<div  role="alert">
                                <strong>${boldText}:</strong> ${displayMessage}
                                <button type="button"  data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                                </button>
                            </div>`
    
        setTimeout(function () {
            message.innerHTML = '';
        }, 5000);
    
    }
}

// Add submit event listener to libraryForm
let libraryForm = document.getElementById('libraryForm');
libraryForm.addEventListener('submit', libraryFormSubmit);

function libraryFormSubmit(e) {
    console.log('You have submitted library form')
    let name = document.getElementById('bookName').value;
    let author = document.getElementById('author').value;
    let type;
    let fiction = document.getElementById('fiction');
    let programming = document.getElementById('programming');
    let cooking = document.getElementById('cooking');
    if (fiction.checked) {
        type = fiction.value;
    }
    else if (programming.checked) {
        type = programming.value;
    }
    else if (cooking.checked) {
        type = cooking.value;
    }

    let book = new Book(name, author, type);
    console.log(book);

    let display = new Display();
    if (display.validate(book)) {

        display.add(book);
        display.clear();
        display.show('success', 'Your book has been successfully added')
    }
    else {
        // show error to the user
        display.show('danger', 'Sorry you cannot add this book.')
    }

    e.preventDefault();
}

HTML File

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
        integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">


    <title>Welcome to Juggu library</title>
</head>

<body>
    <nav >
        <div >
            <a  href="/index.html">Juggu library</a>
            <button  type="button" data-bs-toggle="collapse"
                data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
                aria-label="Toggle navigation">
                <span ></span>
            </button>
            <div  id="navbarSupportedContent">
                <ul >
                    <li >
                        <a  aria-current="page" href="/index.html">Home</a>
                    </li>
                    <li >
                        <a  href="/about.html">About Us</a>
                    </li>
                    <li >
                        <a  href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
                          aria-expanded="false">
                          Websites
                        </a>
                        <div  aria-labelledby="navbarDropdown">
                          <a  href="//allyouneed-notesapp.netlify.app/index.html">AllYouNeed Notes App</a>
                          <a  href="//textutilssystem.herokuapp.com">Text Utils</a>
                          <div ></div>
                          <a  href="//github.com/Mohammedvaraliya">github Profile</a>
                        </div>
                      </li>
                </ul>
                <form  role="search">
                    <input  type="search" placeholder="Search" aria-label="Search">
                    <button  type="submit">Search</button>
                </form>
            </div>
        </div>
    </nav>

    <div id="message">

        <!-- <div  role="alert">
            <strong>Holy guacamole!</strong> You should check in on some of those fields below.
            <button type="button"  data-dismiss="alert" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div> -->
          
    </div>

    <div  id="notes">
        <form id="libraryForm">
            <h1>Juggu library</h1>
            <hr>
            <div >
                <label for="bookName" >Name</label>
                <div >
                    <input type="text"  id="bookName" placeholder="Book Name">
                </div>
            </div>
            <div >
                <label for="Author" >Author</label>
                <div >
                    <input type="text"  id="author" placeholder="Author">
                </div>
            </div>
            <fieldset >
                <legend >Type</legend>
                <div >
                    <div >
                        <input  type="radio" name="type" id="fiction" value="fiction" checked>
                        <label  for="fiction">
                            Fiction
                        </label>
                    </div>
                    <div >
                        <input  type="radio" name="type" id="programming" value="programming">
                        <label  for="Programming">
                            Computer Programming
                        </label>
                    </div>
                    <div >
                        <input  type="radio" name="type" id="cooking" value="cooking">
                        <label  for="cooking">
                            Cooking
                        </label>
                    </div>
                </div>
            </fieldset>
            <div >
                <div >
                    <button type="submit"  id="addBtn">Add Book</button>
                </div>
            </div>
        </form>

        <div id="table">

            <h1>Your Books</h1>
            <table >
                <thead>
                    <tr>
                        <th scope="col">Name</th>
                        <th scope="col">Author</th>
                        <th scope="col">Type</th>
                    </tr>
                </thead>
                <tbody id="tableBody"> </tbody>
            </table>
        </div>

    </div>

    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
    <!-- <script src="js/index.js"></script> -->
    <script src="js/indexes6.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C OGpamoFVy38MVBnE IbbVYUew OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF"
        crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C OGpamoFVy38MVBnE IbbVYUew OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU 6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp tA7hAShOK/B/fQ2" crossorigin="anonymous"></script>
    -->
</body>

</html>

CodePudding user response:

Save it to localStorage in your "add" function, and remove the localStorage item in your "clear" function. Then check localStorage on page load, and populate the UI accordingly.

add(book) {
    // ...
    let booksToAdd = [{
      name: book.name,
      author: book.author,
      type: book.type
    }];
    if ( localStorage.getItem('books') === null ) {
      localStorage.setItem('books', JSON.stringify(booksToAdd));
    } else {
      let data = JSON.parse(localStorage.getItem('books'));
      data.push(bookToAdd);
      localStorage.setItem('books', JSON.stringify(data));
    } 
    // ...
}

clear() {
  // ...
  localStorage.removeItem('books');
  // ...
}

CodePudding user response:

I don't usually write code for others for free, but your app was really exciting and the design was so

  • Related