Maintaining form data while dynamically including more instances of a <div> element to the form

I am currently developing a SpringMVC Webapp with a view that contains a dynamic form. The dynamic elements of the form are listed below:

At the moment, I am passing the variable ${worksiteCount} from my controller to the view (stored in my portlet session - set to 1 by default).

The form submission is handled by an @ActionMapping on the backend.
There is also a button on the page that allows users to add additional engineering worksites as needed - Additional Worksite #1, etc.

When this button is clicked, a @RequestMapping is triggered which updates the "worksiteCount" and returns the view with the extra form fields.

The problem here is: Whenever I click this request, any data filled in the form gets erased.

How can I keep this data persistent within the session? Would utilizing an Ajax Script (preferably using DOJO/Vanilla JS) to increment the variable {worksiteCount} asynchronously on the JSP side be a viable solution?

If yes, how can I achieve this without refreshing the view?
I am relatively new to Ajax-Dojo (such as the dojo.xhrGet/post), Spring framework. Any assistance would be greatly appreciated.

<c:if test="${worksiteCount>1}">
            <c:set var="i" value="0"/>
            <c:forEach var="worksiteAddresses" items="${worksiteAddresses}"> 
            <c:set var="i" value="${i+1}"/>

                <c:if test="${worksiteCount>1}">
                <div class="row">
                <h2 id="worksiteAddress${i}" name="worksiteAddress${i}">Additional Worksite<span>${i}</span></h2>
                </div>
                </c:if>

             <div class="row">
                <div id="f-addr1" class="field">
                    <label>Address1<span><tag:requiredIcon/> </span></label>
                    <input class="" type="text" value="${worksiteAddresses.companyAddressLine1}" id="addressLine1${i}" name="addressLine1${i}" onblur="validateControl('addressLine1${i}');"/>
                </div>
                <div id="f-addr2" class="field">
                    <label>Address2</label>
                    <input class="" type="text" value="${worksiteAddresses.companyAddressLine2}" id="addressLine2${i}" name="addressLine2${i}" />
                </div>              
                <br class="clear" />
            </div>
            <div class="row">
                <div id="f-city" class="field">
                    <label>City<span><tag:requiredIcon/> </span></label>
                    <input class="" type="text" name="city${i}" id="city${i}" value="${worksiteAddresses.companyCity}" onblur="validateControl('city${i}');" />
                </div>
                <div id="f-zip" class="field">
                    <label>Zip<span><tag:requiredIcon/> </span></label>
                    <input class="" type="text" name="zip${i}" id="zip${i}" value="${worksiteAddresses.Zipcode}" onblur="validateZipControl('zip${i}',${i});" />
                </div>
                <br class="clear" />
            </div>

            </c:forEach>
        </c:if>

Answer №1

After carefully considering the situation, it seems that when clicking the button on the page to update the form with new fields for Additional Worksites, there are various approaches to address this issue. One of the more straightforward solutions could be:

1) Pre-load the fields onto the page but keep them hidden, then utilize JavaScript to display them when needed. This method ensures that the existing form data remains intact.

If there is a requirement to fetch additional data from the server-side based on existing information which may alter the data already present on the form, this action should be treated as a submission and managed accordingly by the controller.

2) Either supply all the original data including modifications along with the new fields, or employ AJAX to fetch only the new data in conjunction with the first suggestion.

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

Barba.js (Pjax.js) and the power of replacing the <head> tag

I have been using barba.js to smoothly transition between pages without having to reload the entire site. If you want to see an example, take a look here. Here is a snippet of code from the example: document.addEventListener("DOMContentLoaded", func ...

What is the best way to send an email with a randomly generated HTML output using a <button>?

I am currently working on a feature where a random HTML output is sent to me via email whenever a user clicks on a button on the website page. The user receives a code when they click the button, and I want that code to be emailed to my address automatical ...

What steps can you take to convert your current menu into a responsive design?

I am currently developing a website using PHP, HTML, and CSS. The site is not responsive, and I want to make the menu responsive. My global navigation and admin interface are not adapting properly as they are designed using tables. Is there a method I can ...

To set up MongoDB on your system, execute the following command: `npm install --

I've encountered a problem while attempting to install MongoDB on my personal computer for a Node project. I used the command line and ran npm install --save mongodb. Even though MongoDB appears in the dependencies section of my package.json file with ...

Arranging a nested JSON array directly

Below is the structure of my JSON data : Root |- cells [] |-Individual cells with the following |- Facts (Object) |- Measures (Object) |- Key value pairs |- other valu ...

Troubleshooting HTTP Response Body Encoding Problem in Node.js

When making HTTP requests with the native 'http' module, unicode characters are not displayed correctly in the response body. Instead of showing the actual value, question mark characters appear. Below is a snippet of the code that I am working w ...

The database query did not find any results for 3D secure payments

I have successfully implemented a Stripe integration that utilizes Payment Intents and Stripe Elements' Payment Element, following the guidelines in the Quickstart guide provided by the documentation. Additionally, I have configured webhooks using Spa ...

Sinon - observing the constructor function

While I've come across a few related inquiries, none seem to address what I am specifically looking to achieve. My goal is to monitor a constructor method in such a way that when an object created with the constructor calls this method from a differe ...

Customizing external elements with React's inline styling feature

Trying to use React to style elements generated by a third-party library has been a challenge. In the snippet below, I was able to achieve the desired styling using CSS, but now I am looking to accomplish the same using JavaScript. This way, users can defi ...

What is the best way to set a specific image as the initial image when loading 'SpriteSpin'?

I'm currently working on creating a 360-degree view using the SpriteSpin API. Everything is functioning as expected, but I have an additional request. I need to specify a specific image to be the initial landing image when the page loads. The landing ...

Using Typescript with Material UI Select

I have implemented a dropdown menu using Material UI select labeled "Search By." When the menu is clicked, it displays a list of options. I aim to store the selected option and update the label "Search By" with the chosen option. export default function U ...

What is the best way to change a java.lang.String object into a java.util.LinkedHashMap in

After successfully converting java.lang.String to or.simple.json.JSONObject, I encountered an issue when trying to cast it to a HashMap. org.json.JSONObject jso = new org.json.JSONObject("{"phonetype":"N95","cat":"WP"}"); LinkedHashMap h = (Linked ...

Methods for incorporating JSON Data into ChartJS

Below is my app.js file: app.js var app = angular.module('myApp', []); app.controller('MainCtrl', function($scope, $http) { $http.get('http://happyshappy.13llama.com/wp- json/llama/v1/stats').then(function(response) ...

Displaying Material UI textboxes in multiple columns for dynamically created forms using ReactJs from an array

I am working with an API to retrieve a list of cars, and I have come up with the following code snippet to generate labels and textboxes for editing the car codes. {!carQuery.loading && carDefinitions?.map((car: ICarType, idx: number ...

Incorporating External Content into Your HTML Website

Looking to incorporate third-party content in the form of an HTML page within my own website, I considered utilizing iframes. This would allow me to embed the external HTML page within my site while keeping their libraries and CSS separate from mine. Howe ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

The data that has been retrieved is not currently displayed within the Vue table

I'm currently exploring js/vue and I'm attempting to retrieve data from an API. There's a field where the value is used to fetch data from the API based on that keyword. When I check the console log, I can see that the data is being received ...

Having trouble getting CSS absolute and relative positioning to work with my div slider carousel

I'm currently working on creating a slider carousel using VUE, where the CSS classes (3 divs) are looped through. However, I am facing an issue where every time a div fades out, the next slider creates a duplicate slider at the bottom, resulting in tw ...

Executing Lambda functions on DynamoDB has no effect

Below is the code snippet for a Lambda function: console.log('Loading function'); var aws = require('aws-sdk'); var ddb = new aws.DynamoDB(); function retrieveUser(userid) { var query = ddb.getItem({ TableName: "Users", ...

trigger the focusout event within the focusin event

I am attempting to trigger the focusout event within the focusin event because I need to access the previous value from the focusin event, but the focusout event is being triggered multiple times. $('tr #edituser').focusin(function(){ var ...