简体   繁体   中英

How can I keep the data of a form in my javascript if the submit button reloads the page

I have a simple form with 2 text, 1 number and 1 radio inputs, and I'm trying to take that data into my javascript to create an array of objects created with a constructor, but in the moment I hit the submit button and console log the array it appears empty, I suppose because of the reloading of the page, but I'm not sure.

Here is my javascript code:

 let myLibrary = []; //the array I wantd to fill with the objects const form = document.querySelector('#form'); //the form itself // the constructor function Book (title, author, pages, read) { this.title = title; this.author = author; this.pages = pages; this.read = read; } // the submit listener, which takes the data of the form and sends it as argument of the function that pushes the new object to the array form.addEventListener('submit', (e) => { const data = Object.fromEntries(new FormData(e.target).entries()); addBookToLibrary(data); }); function addBookToLibrary (data) { myLibrary.push(new Book(data.title, data.author, data.pages, data.read)); }

I've tried applying the preventDefault() method to the submit button but that stop the submitting of the form. I also tried doing it with FormData() but I had the same issue.

What I did:

  1. Changed the submit button and add a regular button type button to prevent the page to reload.
  2. Take the data of the form with the "elements" property of the HTML form, which returns a list of all the form controls and can be accessed with an index -> https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements
  3. Create the objects passing the "value" attribute of each element as arguments of the constructor, and push it into the array
  4. Create a click listener for the button, and call the function that creates the objects.

 let myLibrary = []; const data = document.querySelector('#form').elements; // HTMLFormElement.elements const btnSubmit = document.querySelector('#btnSubmit'); // Button type button function Book (title, author, pages, read) { this.title = title; this.author = author; this.pages = pages; this.read = read; } // Take the "value" of each element of the form and create a new Book object function addBookToLibrary (data) { myLibrary.push(new Book(data[0].value, data[1].value, data[2].value, data[3].value)); console.log(myLibrary); } // The listener that calls the function btnSubmit.addEventListener('click', () => { addBookToLibrary(data); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM