Generating fresh object instances and adding them to an array using vanilla JavaScript

I'm currently working on a form that should generate a new object with the input values upon submission, and then add that object to an array.

However, I've noticed that the array seems to be "resetting" itself and not retaining the saved objects.

let myLibrary = []

function Book(title, author, pages, read) {
this.title = title
this.author = author
this.pages = pages
this.read = read
myLibrary.push(this)
}

function checkForm() {
let name = document.querySelector('input[name="title"]').value
let author = document.querySelector('input[name="author"]').value
let pages = document.querySelector('input[name="pages"]').value
let read = document.querySelector('input[name="read"]').checked
new Book(name, author, pages, read)
document.getElementById('library').innerText = JSON.stringify(myLibrary)
}

const submit = document.getElementById('btn1')
submit.addEventListener("click", checkForm);
<input name='title' />
<input name='author' />
<input name='pages' />
<input name='read' />

<button id='btn1'>Click me! </button>
<div >Library:</div>
<div id='library'></div>

Answer №1

To avoid your form from automatically refreshing when the submit button is clicked, you need to listen for the submit event on the form itself and prevent its default behavior. This can be achieved by using the following code snippet:

// Select the form element
form.addEventListener('submit', function(e) {
    e.preventDefault();
    checkForm();
});

Answer №2

To prevent the default submission event of a form in your html, you can use the method preventDefault(). Modify your checkForm() function by adding e.preventDefault() to stop the form from being submitted.

let myLibrary = []

function Book(title, author, pages, read) {
  this.title = title
  this.author = author
  this.pages = pages
  this.read = read
}

function addtoLibrary(title, author, pages, read) {
  let book = new Book(title, author, pages, read)
  myLibrary.push(book)
}


let table = document.querySelector(".table");

myLibrary.forEach(function(e) {
  table.innerHTML += `<tr><td>${e.title}</td>
<td>${e.author}</td>
<td>${e.pages}</td>
<td>${e.read}</td>
</tr>
`
});


// Selectors
let add = document.querySelector("#add")
let submit = document.querySelector("#submit")


function checkForm(e) {
  e.preventDefault(); // prevent the form from being submitted
  let name = document.querySelector('input[name="title"]').value
  let author = document.querySelector('input[name="author"]').value
  let pages = document.querySelector('input[name="pages"]').value
  let read = document.querySelector('input[name="read"]').checked
  addtoLibrary(name, author, pages, read)
  console.log(myLibrary);
}

submit.addEventListener("click", checkForm);
html,
body {
  height: 100%;
}

* {
  font-family: Graphik Regular;
}

ul {
  list-style-type: none;
}

table,
th,
td {
  border-collapse: collapse;
  text-align: left;
  border: 1px solid black;
}

table {
  width: 100%;
}

td,
th {
  height: 50px;
  padding: 10px;
  width: 200px;
  min-width: 100px;
}

th {
  background-color: gray;
  margin-bottom: 50px;
}

.headers {
  margin-bottom: 5px;
}

button {
  background-color: #4CAF50;
  /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin-top: 30px;
}

.pop-container {
  text-align: center;
  /*display: none;*/
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
}

form {
  background-color: gray;
}

input {
  font-size: 20px;
  width: 300px;
  margin-bottom: 5px;
}
<!DOCTYPE html>

<meta charset="UTF-8">

<html lang="en">

<head>
  <link rel="stylesheet" type="text/css" href="style.css">
  </stylesheet>
  <script type="text/javascript" src="http://livejs.com/live.js"></script>
</head>

<body>

  <div class="pop-container">
    <form id="bookquery">
      <input type="text" name="title" id="title" placeholder="Title"></br>
      <input type="text" name="author" placeholder="Author"></br>
      <input type="text" name="pages" placeholder="Pages"></br>
      <p>Have you read it?<input type="checkbox" placeholder="Title" name="read"></p>
      </br>
      <button id="submit">Submit</button>
    </form>
  </div>

  <table class="headers">
    <th>Title</th>
    <th>Author</th>
    <th>Pages</th>
    <th>Read</th>
  </table>


  <table class="table tstyle">
  </table>

  <button id="add">Add new book</button>


  <script src="script.js"></script>
</body>

</html>

function checkForm(e) {
  e.preventDefault(); // prevent the form from being submitted
  let name = document.querySelector('input[name="title"]').value
  let author = document.querySelector('input[name="author"]').value
  let pages = document.querySelector('input[name="pages"]').value
  let read = document.querySelector('input[name="read"]').checked
  addtoLibrary(name, author, pages, read)
}

Answer №3

None of the previous solutions worked for me, so I decided to provide a simplified example that actually works. In order to make things work smoothly, I always opt for simplifying as much as possible.

index.html

<html>
  <header></header>
  <body>
    <div>
        <form id="myForm">
            <label for="title">title:</label><br>
            <input type="text" id="title" name="title" value="title"><br>
            <button id="submit">Submit</button>
        </form>
    </div>
    <script type="text/javascript" src="functions.js"></script>
  </body>
</html>

functions.html

let myLibrary = [];

function Book(title) {
  this.title = title;
  myLibrary.push(this);
}

function checkForm(){
  let title = document.querySelector('input[name="title"]').value;
  new Book(title);
  myLibrary.forEach(function(element) {
    console.log(element);
  });
}

document.getElementById("myForm").addEventListener(
  'submit',
  function(e) {
    e.preventDefault();
    checkForm();
  }
);

I'll leave it up to you to reintroduce the other fields in the Book object.

Answer №4

It's uncertain because I've attempted to demonstrate that your code effectively saves the object. It is possible that your form is causing a page refresh... which could be the culprit. However, based on the provided code, everything seems to be functioning as intended.

let myLibrary = []

function Book(title,author,pages,read) {
    this.title = title
    this.author = author
    this.pages = pages
    this.read = read
    myLibrary.push(this)
}

function checkForm(name,author,pages,read)
{
  new Book(name, author, pages, read)
}

checkForm("Chris", "Jerry", "56", "65");
checkForm("Sean", "John", "56", "65");

// Both Objects are still stored...
console.log(myLibrary);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Focus is lost on React input after typing the initial character

Whenever I input text, the focus is lost. All my other components are working fine except this one. Any ideas why this might be happening? I attempted to create separate components and render them in my switch statement, but it still doesn't work. O ...

Designing a popup using Angular, CSS, and Javascript that is capable of escaping the limitations of its parent div

I'm currently working on an Angular project that involves components nested within other components. My goal is to create a popup component that maintains the same size and position, regardless of where it's triggered from. One suggestion I rece ...

Html content overlapping div rather than being stacked vertically

My goal is to arrange a group of divs inside another div in a vertical stack. However, I am facing an issue where the text from the last div is overlapping with the second div instead of following a proper vertical alignment where the text in the third div ...

The Cascading of Bootstrap Card Designs

Looking for some assistance with my TV Show Searcher project that is based on an API. The functionality is complete, but I'm struggling to get the Bootstrap cards to stack neatly without any empty space between them. I want it to resemble the image ga ...

Is there a way for me to delay sending an immediate response until the asynchronous loop has completed?

Currently trying to implement something similar to the code snippet below. I suspect that the issue lies within the asynchronous call as it seems like the response I am getting is always an empty array, despite the API returning data. As a beginner in th ...

Issues with Bootstrap Contact Form submission

I found a helpful tutorial for creating a form at the following link: After following the tutorial, I added these scripts to the bottom of my contact form HTML: <script src='https://code.jquery.com/jquery-1.12.0.min.js'></script> ...

By turning off the autosave feature in WordPress, you can prevent the Confirm Navigation window from popping up when exiting an unsaved page

I successfully disabled autosaving drafts on Wordpress 4.3 by using the code wp_dequeue_script('autosave'). However, I noticed that the window with leave confirmation message: Are you sure you want to leave this page without saving... is no ...

Generate a Vue Component in real-time with a click of a button

My task involves populating a list of orders using the orders array. Each order has an edit functionality that triggers a vuetify dialog box component when clicked, displaying default data for editing. Here's my current approach: <tbody class=" ...

Initiate ajaxForm submission again if necessary

Utilizing the ajaxForm function to transmit data to a PHP background process while some JavaScript functions monitor the asynchronous operation. In cases of failure, such as internet or electricity disruptions, I want users to have the ability to retry the ...

Using JavaScript to trigger wake on LAN directly from a web browser

Can a wake on LAN command be sent to a computer on a local network from a browser without using server side code? I am in control of the entire network. My goal is to send the command from a tablet browser over wifi to a wired computer on the same LAN. I ...

What is causing my conditional operator to malfunction?

What is the reason for the output being undefined instead of "old" in this scenario? function test(age) { return 12 < age ? "old" : "young"; } test(15); ...

Learn how to dynamically display an image if the original one fails to load by utilizing the image component available in Next.js

I am currently fetching data for an image. The source of the image is stored in the variable "movie.primaryImage.url". However, there are instances when the image fails to load. I have attempted to implement conditional rendering so that a fallback image ...

Sending props to a component without causing it to render(Note: This is

I am trying to figure out how to pass props from one component to another component without rendering a new component on the same page. I want to send the props selects from /memo to /memo/start using the function startMemo(). Code: Memo.js import React, ...

Is there a way to retrieve the ID of an input field dynamically using jQuery when a button is clicked, and then store it in

I am relatively new to JavaScript and jQuery, so I could use some help or suggestions on how to tackle this task. My task involves retrieving the dynamic IDs of input fields upon button click. I have a total of 100 dynamic input fields. <input id="Pro ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

What could be the cause of a JSON string only returning the final object when evaluated?

Does anyone have insight into why only the last object in my json string is returned when I use the eval function? ...

The mysterious case of the vanishing close button on Curator.io's mobile

Currently, I am using curator.io aggregator to showcase my Instagram feed on the website. An issue arises when switching to mobile view as the close button (class="crt-close") disappears. You can see an example of this here: To replicate the pr ...

The client side isn't providing the JSON data

I need assistance with sending JSON data from the client side to the server side. On the client side: function sendData() { var formData = { first: $("#name").val(), last: $("#lastname").val() } console.log("Sending data: " + ...

How can I retrieve checkbox data from a database using PHP and jQuery?

I'm attempting to showcase the checkbox values from the database as follows: Array ( [0] => Array ( [userid] => 868 [username] => Pavanasri [firstname] => Pavana [email] => &l ...

Implementing an ES6 class in a next.js application: A step-by-step guide

Currently, I am in the process of developing a next.js application and am looking to extract the code that interacts with the database from the API. To achieve this, I have developed a class that serves as a manager: class UserManager { async findUser ...