Ensuring the persistence of div contents

I am facing a unique challenge and could use some assistance.

Below are two segments of HTML:

<div id="main_">
<ul class="unstyled">
    <ui:repeat var="adultPassenger" varStatus="adult" value="#{bean.adultPassengers}">
        <li>
            <div id="adult#{adult.index}" class="hitbox_">
                <div id="passengerTitle">Adult #{passengerDetailsBean.getPassengerCount(adult.index)}</div>
            </div>

            <div class="hide">
                <div id="adult#{adult.index}_form">
                    <div>
                        <div>
                            <div class="pull-left" style="width: 50%;">
                                <div><h:inputText value="#{adultPassenger.firstName}" class="pasFirstName_adult#{adult.index}" label="First Name"></h:inputText></div>
                            </div>
                            <div class="button-container">
                                <h:commandButton value="Continue" styleClass="btn btn-warning btn-large btn-block" onclick="handleDetailsClick('adult#{adult.index}')"></h:commandButton>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </li>
    </ui:repeat>
</ul>
</div>

and

<div id="secondary_" class="hide">
    <table>
        <tbody>
            <tr>
                <td">
                    <h:commandButton id="secondaryBack" value="Back" styleClass="btn btn-warning">
                    </h:commandButton>
                </td>
                <td class="secondaryTitle">
                    <h3 class="page-title orange-title-big">Passenger Details</h3>
                </td>
            </tr>
        </tbody>
    </table>

    <div id="secondaryContents">

    </div>
</div>

Both segments are on the same page, where one div is visible while the other is hidden. I am using the following JavaScript:

$(".hitbox_").click(function() {
    var round = Math.round;
    var id = $(this).attr("id");

    window.alert(id);

    var f = $("pasFirstName_"+id).get();
    console.log("name " + f.value);

    // set contents of secondary div
    var passengerDetails = $("#" + id + "_form").html();
    $("#secondaryContents").html(passengerDetails);

    $("#main_").toggleClass("hide");
    $("#secondary_").toggleClass("hide");
});

function handleDetailsClick(index) {
    var passengerDetails = $("#" + index + "_form").html();
    $("#secondaryContents").html(passengerDetails);

    $("#main_").toggleClass("hide");
    $("#secondary_").toggleClass("hide");
}

The objective I am trying to achieve: Hide the first div when clicked, show the second div with the content from the hidden form in the first div. This allows me to retain class names as there may be multiple forms like this.

When "Continue" is clicked, hide the second div and pass back its contents to the first div to preserve entered details on the form.

The issue I am facing is that the details entered do not persist. When clicking the same div again after filling out the form previously, it should display the form with the previous details entered.

Unfortunately, the form always appears empty. Can anyone help identify what might be causing this problem?

Answer №1

Identifying the issue lies within these lines of code

var passengerDetails = $("#" + id + "_form").html();

$("#secondaryContents").html(passengerDetails);

The current approach involves extracting HTML from one div and inserting it into another. While this action will replicate the HTML content in the target div, it won't preserve any user input values or event bindings.

A better alternative would be to select the element and append it to the target

var passengerDetails = $("#" + id + "_form").children();
$("#secondaryContents").append(passengerDetails);

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

Identify the specific button that triggers a JavaScript function

Currently, I am working on an admin page that displays a list of posts using EJS for template rendering engine. <table> <tr> <th>Name</th> <th>Description</th> </tr> <% projects.for ...

Having trouble getting a background image with tint to display properly in Bootstrap

I applied a sleek black transparent gradient to my body background picture, but as soon as I integrated bootstrap into the HTML code, the effect ceased to function. body { background: linear-gradient( rgba(0, 0, 0, 0.5), rgba ...

Steps for displaying an HTML table in Excel by clicking on a button

My goal is to open an HTML table in XLS format with a single click of a button. Currently, I have a JavaScript function that allows me to export the HTML table to XLS using the "save as" option. However, I want to enhance this functionality so that clickin ...

Employ JavaScript regular expressions to extract all the text values from VBA code

Looking to utilize JavaScript regex in order to extract all string values from VBA code. For instance: If cmd = "History Report" Then Range("D2").Formula = "=TEXT(""" & createDate & """,""" & Replace(subtitleFormat, """", """""") & " ...

Issues with displaying Angular 6 NGX chips correctly

Currently, I am utilizing `ngx-chips` in my projects and storing my objects in an array. This allows me to use the following example: <div> <h3>Tags within an autocomplete component (clear on blur events)</h3> <tag-inp ...

Is it possible to make a div resize to fit its container?

I have a square block measuring 100*100px. The container block it is within can be resized. I need the inner block to adjust its size dynamically so that it always fits inside the parent container without overflow and maintains its square shape. Important ...

Flexbox ancestor causing Bootstrap 5 Carousel width to double

A peculiar issue arises with the Bootstrap 5 Carousel placed inside a Flexbox where it unexpectedly expands in width (pushing other flex-items aside) when transitioning between images. This behavior persists even when the immediate container is set to disp ...

What is the best way to inject child nodes into parent nodes without causing the view to shift to the location where the element is being

While I am rendering elements and appending them to a parent div, my screen keeps jumping to the bottom-most element as it loads instead of maintaining the current view. Ideally, it should start at the top of the screen and remain there without any sudden ...

Searching for an array of objects within a MongoDB collection using queries

I have a collection where I store information in an array of objects named Degrees. Each object in this array has keys like {Uni:'',Level:'',Degree:''}. I am trying to create a query that will help me find documents with a de ...

Using JSON and Ajax to dynamically append and generate a new Div element

I am currently working on an HTML page where most of its components are static and loaded from JSON files. My goal is to create "posts" and attach "comments" to them. I have two JSON files for this purpose: posts.JSON and comments.JSON. The posts.JSON fi ...

How can I resolve the issue of <td> being repeatedly displayed five times instead of just twice in PHP?

Can someone assist me with fixing this for loop issue? I am trying to display controls next to each item in the row, but it is showing 5 sets of controls instead of just 2. <tbody> <?php //retrieve list of supplies $numOfRows = 0; $result = my ...

How null data is transferred between views and controllers in ASP.NET Core

Is there a function in my controller to check if the user email is active or not? public async Task<IActionResult>ActiveEmailAccount(EmailActiveAccountViewModel active) { if (ModelState.IsValid) { ...

A guide on utilizing setTimeout for repeatedly executing a function

I am facing an issue with my slideshow containing 4 pictures and pagination. I want the pictures to be displayed one by one in a loop, so I tried using the following code: function displayPictures(intervalTime) { setTimeout('$("#picgallery_pagging li ...

Encountering the below error message when running the command to initialize expo project:

Dependency installation in progress... Warning: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="accfc3dec981c6dfec9d829e829b">[email protected]</a> is deprecated, consider upgrading to core-js@3 or a ne ...

I keep encountering the issue of receiving a "name undefined" error message while attempting to make a post request with Express and Body Parser

I've been working on building a MEAN app and encountered an issue while testing POSTing with POSTMAN. Every time I attempt to POST, I receive the error message "TypeError: Cannot read property 'name' of undefined". Strangely enough, if I inp ...

Searching for an object in a more efficient manner

At times, I often find myself needing to locate a specific object within an array of objects where the key I am searching for matches a particular value. For instance: var cars = [ { id:23, make:'honda', color: 'green' }, { id ...

Nested Flexbox Elements

Looking to nest elements using flexbox in order to achieve the following layout: https://i.sstatic.net/bEKps.png Does anyone know how to make this happen? ...

Clearing all data in a form upon opening

Within a single portlet, I have organized two forms under separate tabs. What I am aiming for is that whenever I switch to tab 2, all fields within its associated form should automatically be cleared without the need for a button click. Even after attempti ...

Display the information in real-time as it is being transmitted to the backend

I'm facing a challenge with the user experience. Currently, I am developing a chat application using Ionic, Angular, and Firebase. The issue at hand is that messages are only displayed once they are successfully sent to the server. This means that o ...

Redirecting to a different page using Jquery

Is there a way to update the status without being redirected to base_url().'/Admin/Jobs/' every time? Code: <?php if ($key['status'] === '1'): ?> <?php echo form_open('Admin/update_job_status'); ?> < ...