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

Is there a way for me to utilize WordPress functions within my PHP script that is being called via AJAX?

Is there a way to make the 'POST' side branch of my PHP script 'WordPress-aware' so that I can call native WP functions from within it? The situation is as follows: I am trying to call a WordPress function (get_avatar($id)) from a PHP s ...

Executing synchronous functions in NodeJS

I've been attempting to retrieve the number of records from a database using Node.js, but I'm running into an issue with synchronous requests. When I try to print the number inside the function, it works fine, but outside the function, it doesn&a ...

Each loop iteration results in the array being randomly ordered

My goal is to store multiple objects in an array and then render them out in a specific order. This is my process: app.js var allOdds = []; var count = 0; // ===================================== /* Database Configuration and Error Handling */ // ====== ...

The initial render of Next.js is not properly loading the CSS files

Encountering an issue with the initial load of the mobile app version; it seems that the CSS of my component covering the page is not loading correctly on the first screen load. However, when resizing to desktop and then switching back to mobile view, the ...

Developing clickable hyperlinks within a jQuery Datatable

I am currently in the process of transitioning from an asp.net GridView Control to a jQuery DataTable with Ajax. On my project's home page, I have a visually appealing image grid that is justified. Each image in this grid acts as a link, redirecting u ...

Here's a unique version: "Discovering how clients can easily connect to a new room using socketio

There are 5 rooms on my server named "A", "B", "C", "D", and "E." Server-Side In the server side code: io.on('connection', (socket) => { console.log('New user connected'); socket.on('disconnect', () => { ...

Launching a React build using Docker on Apache or AWS

I am a beginner to the world of docker and react. My goal is to successfully deploy a production build on AWS. Here are the steps I have taken so far: Created a dockerfile. Built and ran it on the server. npm run and npm run build commands are functionin ...

Resetting the countdown timer is triggered when moving to a new page

In my current project, I am developing a basic battle game in which two players choose their characters and engage in combat. The battles are structured into turns, with each new turn initiating on a fresh page and featuring a timer that counts down from ...

I often find myself feeling unsure when I incorporate conditional logic in JSX within Next.js

Hello, I am currently using Next.js and encountering an issue with using if/else in JSX. When I use if conditions, the classes of elements do not load correctly. Here is my code: <Nav> { login ? ...

Obtain JSON information and integrate it into an HTML document with the help of

I am currently working on a PHP/JSON file named users-json.php. <?php include_once('../functions.php'); if (!empty($_GET['id'])) { $GetID = $_GET['id']; $query = "SELECT Username, Firstname WHERE UserID = :ID"; $stmt = $d ...

I am having difficulty retrieving the JSON object that was sent by the servlet

$(document).ready(function() { var path = null; console.log('${pageContext.request.contextPath}/loadfile'); $.ajax({ dataType: "json", url: '${pageContext.request.contextPath}/loadfile&apos ...

Defining the range of an array of numbers in TypeScript: A complete guide

When working with Next.js, I created a function component where I utilized the useState hook to declare a variable for storing an array of digits. Here is an example: const [digits, setDigits] = useState<number[]>(); I desire to define the range of ...

Utilize Google Tag Manager to search and substitute characters within a variable

Within my GTM setup, I have a CSS selector variable in the DOM. This variable pertains to real estate and specifically represents the price of a listing. My goal is to eliminate the characters ($) and (,) from this variable as part of meeting the requireme ...

The div structure generated through JavaScript appears distinct from its representation in the live DOM

Currently, I am facing a challenge with creating a complex nested Div structure within a JavaScript loop that iterates over JSON response objects from the Instagram API. The main goal is to set the URL for each image within a specific Bootstrap div layout. ...

Is the return type determined by the parameter type?

I need to create an interface that can handle different types of parameters from a third-party library, which will determine the return type. The return types could also be complex types or basic types like void or null. Here is a simple example demonstra ...

What are the most effective ways to manage state in form components using React?

As I delve into the realm of best practices for managing state in React components, I find myself grappling with different approaches. Initially, I crafted a form by creating a TextField component structured like this: var TextField = React.createClass({ ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

Trouble arises with the MUI 5 date picker when inputFormat is included

When I select a date from the calendar, everything works fine. However, if I set inputFormat="yyyy/MM/dd" and manually type in the date, it doesn't recognize the date format properly. Instead, it treats the input as a string like 11111111111 ...

Using a jQuery UI accordion with a numbered list

As part of my company's user documentation, I am trying to integrate jQuery UI components into our HTML output. Despite my limited experience with JavaScript, I was able to get the accordion feature working for table rows. However, I am now facing dif ...

Exploring jQuery: Implementing a SlideDown Effect on Loading Questions

Greetings, this is my debut post on stackoverflow. I have been an avid reader and learner here. I am currently using a jQuery function to load posts in WordPress themes using the .load function. However, I am facing a challenge that I cannot resolve on m ...