Strategies for retaining additional fields added via JavaScript when the page is refreshed

  var newField = document.createElement("lastExp");
  newField.innerHTML = 'insert new form field HTML code here';
  document.getElementById("lastExp").appendChild(newField); 

I have a button that adds an additional form field with a simple click. My question is, how can I ensure that these extra fields are not lost when I refresh the page?

Answer №1

While Stack Overflow is not the ideal platform for writing code, I have included a minimal example here just in case someone other than the OP needs it.

This example focuses on using localStorage and serves as a starting point. It's important to note that you will need to append the element every time the page loads.

Unfortunately, the snippet provided won't work here due to the sandboxing of iframes. You can visit my hub to experiment with it.

var container = document.getElementById('container'),
    toggle    = document.getElementById('toggle');
    element   = null;

// initial check
init();

// add click event and listen for clicks
toggle.onclick = function() {
  // both cases will update localStoage _inputIsThere
  // if element is null -- doesn't exists, then add it
  if (element == null) {
    add();
  } else {
    // remove the element 
    remove();
  }
}

// check if key exists in localStorage; this is where all the "magic" happens.
function init() {
  var exists = localStorage.getItem('_inputIsThere');
  if (exists && exists == 'true') {
    add();
  }
}


function remove() {
  element.remove();
  element = null;
  // update key in localStorage to false
  localStorage.setItem('_inputIsThere', false);
}

// adds the input and updates 
function add() {

  var e = document.createElement('input');
  e.type = 'text';
  element = e;
  container.appendChild(e);
  // update key in localStorage to true
  localStorage.setItem('_inputIsThere', true);

}
<button id="toggle">Add/Remove</button>
<div id="container"></div>

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

Leveraging AngularJS for retrieving the total number of elements in a specific sub array

I'm currently working on a to-do list application using Angular. My goal is to show the number of items marked as done from an array object of Lists. Each List contains a collection of to-dos, which are structured like this: [{listName: "ESSENTIALS", ...

Ensuring that a service is completely initialized before Angular injects it into the system

When Angular starts, my service fetches documents and stores them in a Map<string, Document>. I use the HttpClient to retrieve these documents. Is there a way to postpone the creation of the service until all the documents have been fetched? In ot ...

Troubleshooting JavaScript for Sidebar Disappearance due to marginRight and display CSS Issue

I need to adjust the layout of my website so that the sidebar disappears when the window is resized below a certain width, and then reappears when the window is expanded. Here is the HTML code: <style type="text/css"> #sidebar{ width:290 ...

Iterate through a JSON object using JavaScript, with distinct keys but the same object structure

Hello, I'm currently in the process of creating a slider using images sourced from a json file. Here is the json structure that I am working with: { "info":[ { "slide1":[ { "title" ...

Tips for adding a "Select All" feature to a dropdown list?

Currently, I have a dropdown list with a filter for IN and OUT values. The functionality is working as expected: <select class="form-select" style="max-width: 100px" [ngModel]="selectedBrand" (ngModelChange)="onChangeT ...

Bot in Discord designed to provide varying tiered rewards for designated roles on payday

I'm trying to configure the bot to distribute different amounts of payment to various roles. However, no matter what I attempt, it keeps indicating that the role is undefined. Being new to JavaScript and coding in general, I've researched this ...

Instructions on adjusting the image size within a MUI Card

import { Card, CardActionArea, CardContent, CardMedia, Typography, } from "@mui/material"; import React from "react"; import { styled } from "@mui/material/styles"; const CardImage = styled("div")(({ theme ...

What is the best way to extract words from a string within a textarea using javascript?

Currently, I am focused on improving my skills in JavaScript and HTML. In one of my projects, there is a text area where the user inputs a CSV format like this: 17845 hello bye 789 After input, I get 17845,hello,bye,789. Now, the challenge is t ...

Displaying [object Object] in Angular Material datatable

I am currently working on implementing a datatable component using Express and Firebase DB. Below is the service request data: getText() { return this.http.get<nomchamp[]>(this.url) .map(res => { console.log(res); return res }); ...

Using SVG graphics as data labels in a HighChart stacked column chart

I am attempting to generate a stacked column chart in Highcharts with SVG images as x-axis labels, similar to the image displayed here: https://i.stack.imgur.com/y5gL1.png I have managed to achieve this with individual data points per label (non-stacked ...

React maintains the state of just a single element within an array at a time

I'm faced with a roadblock while developing my covid19 application. The app should display a list of countries on the left side of the screen, allowing users to add any number of countries to the right side for more detailed covid data. I'm still ...

Create a dynamic onClick event script and integrate it into Google Optimize

I need to incorporate a button element into my website using Google Optimize for an experiment. This button needs to trigger a specific script depending on the variation of the experiment. I have attempted two different methods: <button id="my-button" ...

"Executing ng-click directive on a second click changes the route in AngularJS

Why does my ng-click only redirect to a new location on the second click? It should redirect to $location.path('/login.signin');, but it only works if I click the button again. It's strange. Where could this issue be originating from? Belo ...

Issues encountered while using the rest operator with jQuery .when method

We have implemented a wrapper in our code base for handling ajax calls using jQuery. The purpose of this wrapper is to make it easier to eventually switch away from jQuery, if needed, by isolating all ajax-related calls. Below is the definition of the wrap ...

Transmitting form information to a nested page within a div container

This is my fourth attempt to seek an answer to this question, as I've faced downvotes in previous attempts. So here we go again. I am trying to send data from a hidden input within a form using ajax. The value of the hidden input is generated by a php ...

Why is the responseText from XMLHttpRequest always stripped of tags in AJAX?

Whenever the server sends the XML string to the client using the XMLHttpRequest object, I noticed that when I insert the text inside the div tags, it appears without any tags. However, I actually need the XML tags to be present so that I can parse the cont ...

Can we safely save a value in session storage directly from the main.js file in Vue?

Throughout the user session managed by Vuex, I have a session storage value set to false that needs to be monitored. Setting up this value directly from the main.js file looks like this: import { createApp } from 'vue'; import App from './Ap ...

HTML5 Boilerplate and optimizing the critical rendering path by deferring scripts and styles

Previously, I constructed my website layouts using the HTML5 Boilerplate method: incorporating styles and Modernizr in the head section, jQuery (either from Google CDN or as a hosted file) along with scripts just before the closing body tag. This is an exa ...

Encountered an issue while trying to use Figma's spellchecker extension

Despite following the instructions in the readme carefully, I am facing difficulties running the Figma spellchecker extension. Executing npm run build goes smoothly. But when I try to run npm run spellcheck, I encounter an error message in the console: co ...

Ways to determine the presence of a value in an array using AngularJs

I'm currently working on looping through an array to verify the existence of email, phone, and alternate phone in a database. My challenge lies in finding a suitable function or workaround in AngularJS that allows me to iterate through the array with ...