Attempted to remove Child Div using Jquery, but it did not get removed as expected

Trying to remove child divs inside a parent div? There are several methods, such as:

 $(".ChildDiv").html("");
 $('.ChildDiv > div').remove();
 $(".ChildDiv").html("");
 $("#ParentDiv").html("");
 $(".ChildDiv div").remove();
 $(".ChildDiv div").empty();
 $('.ChildDiv ').find('div').remove();

I have listed all possible ways to remove the divs, but I am still unable to clear all the divs inside the Parent Div. Let me explain my situation.

Scenario :

I have two containers - container-1 with an input search box where I can search for employee names and select a few employees (e.g., 5). By clicking the "Add" button, I can move these selected employees to another container-2 which is a 'div'.

https://i.sstatic.net/Sbsjb.jpg

When I click on the report button event to get information about those 5 people in separate ASPX pages, then return to the page to search for more employees, it adds the last searched group of 5 employees to the new selection of 3 employees instead of just adding the new 3 employees.

https://i.sstatic.net/ZI80N.jpg

https://i.sstatic.net/kS6Uo.jpg

To prevent this, I am trying to clear the previous 5 employees from that div after clicking the "Report" button. Even though the alert says there are 0 elements, when I add the data again, it appends the previous set along with the new one, which is undesired behavior. Here is my code:

Things to keep in mind: 1. ParentDiv is container-2 2. ChildDiv is the dynamically appended child div inside ParentDiv when selecting 5 employees on "Add" button click

Here is the HTML code:

 <table id="topTable">
    <tr>
        <td id="leftpane">
             <h4>Search for Employee by Name or Profile:</h4>
             <input type="text" id="EmployeeSearchBox" class="search-box" aria-multiselectable="true" />
             <select id="EmployeeList" size="20" multiple></select>
        </td>
        <td id="centerpane">
            <div> <input type="button" value="Add >>" class="AddButton" id="buttonAdd" /></div>                
            <div> <input type="button" value="Add All >>" class="AddButton" id="buttonAddAll" /></div>

        </td>
        <td id="rightpane">
             <h4>Selected Employees:</h4>
    <div id="ParentDiv"></div>
        </td>
    </tr>
</table>

Run Report button event

 <input class="data" type="submit" name="cmdSubmit" value="Run Report" onclick="return FormValidate();"
                    onserverclick="RunReport" runat="server" id="Submit1" />

Add Button Click : which moves the employees from container-1 to container-2.

 $(document).on('click', '#buttonAdd', function (e) {       

    $('#EmployeeList :selected').each(function (i, selected) {           
        myHash[$(selected).val()] = $(selected).text();
    });

    var myNode = $("#ParentDiv")[0];

    while (myNode.firstChild) {
        myNode.removeChild(myNode.firstChild);
    }
    for (var emp_id in myHash) {
     var emp =   $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>&times;</Span> </div>");            
    }  
    $('#EmployeeSearchBox').val("").trigger('input');  
});

Even though I've tried clearing the elements from ParentDiv/ChildDiv upon clicking the "Report" button, they are not being removed. How can I fix this issue?

This is a sample of the "Report" button event code:

function FormValidate() {//Part of my other code
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
  }

None of these methods seem to be working. It appears there may be an issue with the "Add" button event where the data is being stored improperly.

NOTE :

I want to avoid clearing the array of employee lists so that I can select multiple employees repeatedly. For example, I could select 2 employees starting with the letter "M," followed by 2 employees with the letter "L," and so forth. The container should retain all selected employees before the "Report" button is clicked.

Let me know if this explanation is clear enough.

Console Log

https://i.sstatic.net/WkRUh.jpg

Answer №1

At last, the issue has been resolved successfully. I have managed to fix the problem that I was encountering, and now everything is working as expected.

 $(document).on('click', '#buttonAdd', function (e) {

    var div_count = $('#ParentDiv').find('div').length;
    if (div_count === 0) {
        myHash = []; // Resetting the hash to add new employees if Container-2 is empty.
        $('#EmployeeList :selected').each(function (i, selected) {
            myHash[$(selected).val()] = $(selected).text();
        });
    } else { // If there are existing employees in Container-2, append more.
        $('#EmployeeList :selected').each(function (i, selected) {
            myHash[$(selected).val()] = $(selected).text();
        });
    }

    var myNode = $("#ParentDiv")[0];
    console.log(myNode);

    while (myNode.firstChild) {
        myNode.removeChild(myNode.firstChild);
    }
    for (var emp_id in myHash) {
        var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>&times;</Span> </div>");
    }
    $('#EmployeeSearchBox').val("").trigger('input');
});

My Approach

As I needed to be able to append multiple employees by searching, I handled that in the 'else' part. When generating the "Report", I clear Container-2.

Upon returning to the page to search for more employees, Container-2 will not have any employees, so

var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
 myHash = [];
 //....
 }

This clears the array and allows me to add fresh employees, effectively solving the problem :)

Thank you all for the assistance.

Answer №2

Revised for clarification:

It is essential to reset the myHash variable to avoid duplicating employee entries.

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

How can I retrieve the value of $_POST[] immediately after a selection is made in a dropdown box

Is there a way to retrieve the $_POST value immediately after changing the select option without having to submit the form? <select name="cat_id" class="form-control" onChange="this.form.submit();" style="width:300px;"> <?php ...

Tips for inserting an additional value into the DevExpress grid pager dropdown in an ASP.NET C# application?

Is it possible to add an additional value "ALL" into the DevExpress grid pager dropdown? Currently, the dropdown displays the following settings: <PageSizeItemSettings Items="10,20,50,100" Visible="True"> </PageSizeItemSettings> I would ...

Is there a way to trigger the "day click" event when the "Event Click" is clicked on in Jquery full calendar?

When using a jQuery calendar, there are options for day click and event click functionality. I am specifically trying to only handle the "day click" event, even if an "event" is clicked. In order to achieve this, I have commented out the event click functi ...

Deactivating controls while displaying the loading bar in AngularJS

I'm currently working on a web application using AngularJS. I want to incorporate a loading bar to signify long data load times from the server. To replicate heavy data loads, I am utilizing $timeout to trigger the loadbar when the operation begins a ...

Different ways to swap table cells using only CSS

Does anyone know how to switch the positions of table cells using only CSS? I have three divs set up like this: #content { width: 1000px; display: table; float: none; vertical-align: top; border: 1px solid red; } #left { float: left; } #ri ...

Utilizing the same WebDriverJS instance repeatedly

As a beginner in Selenium, I successfully launched a website using the following Node.js code snippet: var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder() .forBrowser('chrome') .build(); console ...

Sending a variable to a function in JavaScript (winJs) from a different function

Greetings! Currently, I am developing a Windows 8 app using Java Script. function fetchFromLiveProvider(currentList, globalList,value) { feedburnerUrl = currentList.url, feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&outpu ...

Loop through each item and store them in an array of objects

I have created the following jQuery code : <script type="text/javascript"> $(document).ready(function () { var school = { name: 0, url: 1, location: 2 }; var schools = []; $(".name").each(function (key, value) { ...

The ASP.NET AddWithValue method adds value to the application with ease

Using the AddStringWithValue method in ASP.NET using C# The HTML code appears as follows: <form class="login-modal-content animate" action=""> <asp:Login ID = "Login" runat = "server" OnAuthenticate="ValidateUser"></asp:Login> ...

Adjust the size of the embedded iframe to match the dimensions of the containing div

Is there a method to resize the iframe embed code for a vine so that it fits within the boundaries of the enclosing div? The supplied embed code already includes sizing information as shown below: <iframe src="https://vine.co/v/iMJzrThFhDL/embed/simp ...

Issue with drop-down menu functionality on mobile-friendly website

After deciding to revamp my website for responsiveness, I encountered an issue with the menu not displaying on smaller screens. Everything else is functioning correctly except for the drop-down menu! Here is the HTML code: <!doctype html> <html ...

Redirecting to a specified URL after submitting a POST request in Angular

I recently started learning Angular and decided to follow this tutorial on creating a MailChimp submission form. I made sure to customize the list information & id according to my own needs. However, after submitting the form, I encountered an issue wh ...

Ways to convert a JavaScript object's properties into JSON format

I am currently manually going through the properties of my javascript class to create JSON, as shown below. It feels cumbersome and I am looking to automate this process so that I don't have to make changes to the 'toJson' function every tim ...

Showing a pop-up on a click of a dynamically created table row, showcasing information specific to that row

I am facing a challenge with my dynamically generated table that is based on the JSON response from an AJAX call. What I am trying to achieve is to display additional data in a modal when a table row is clicked. This would be simple if the data was hard co ...

The PHP AJAX call is returning an undefined response status

I'm facing two issues here. The first problem is that when I try to access response.status, it returns undefined. The second issue is related to the creation of "$_SESSION['promo-code'] = $arr". When I enter a promo code, I encounter the fol ...

Streamline your Salesforce application by automating drop down selections with XPath using Selenium WebDriver

https://i.stack.imgur.com/Eg9jc.pngAn application has been developed in Salesforce with a dropdown box containing items built using the <li> tag. However, I am unsure how to select a specific item from this design. <div id="Department__cformContr ...

What methods can I use to prevent caching of XMLHttpRequest requests without relying on jQuery?

I am currently working on a web application that refreshes a table every minute from an XML file. However, I have noticed that when I make edits to the content of the XML file, I see a "304 Not Modified" message in the script log when trying to retrieve th ...

Text input in Bootstrap not reaching full width

Trying to achieve a Bootstrap textfield embedded in a panel that spans 100% of the remaining space-width within the panel. However, this is the result obtained: The blue border represents the edge of the panel. Below is the code being used: <div clas ...

Transform the C# DateTime to LocalTime on the client side using JavaScript

Utilizing the Yahoo API on my server to retrieve currency information can be done through this link: Yahoo Currency API This API provides me with both a Date and a Time, which I'd like to combine into a single DateTime object. This will allow me to e ...

Strategies for extracting special character codes from API data within a React functional component

I have been experimenting with a simple trivia API to improve my understanding of REACT. I have noticed that the question data is returning with special character codes, which is causing issues with react jsx. Can anyone suggest a method to easily convert ...