JQuery div not cooperating with other JavaScript/jQuery functions

I used the $(select).append() method to add one div inside another div, but I wanted to close it on click of an image. So I added an image and another $(select).button().click( { $(select).hide() }) to achieve this functionality. However, when clicking the close image, nothing happens...

$(document).ready(function() {
            $("#subCre").click(function() {
                cust = $("#customer").val();
                address = $('#address').val();
                phone = $('#phone').val();
                amt = $('#initamount').val();
                user = '<%= session.getAttribute("user").toString()%>';
                type = '<%=session.getAttribute("type").toString()%>';
                alert(cust + address + phone + amt + user + type);
                $.post("../processor/proc2.jsp",
                        {
                            customer: cust,
                            address: address,
                            phone: phone,
                            initamount: amt,
                            user: user,
                            type: type
                        },
                function(data, status) {
                    if (status === "success") {
                        if(data.length == 11) {
                            $("#SystemMessages").append('<div class="Msg draggable"><img class="close" src="../mime/close.png">Account Added</div>'); // **Here one div
                        } else {
                            $("#SystemMessages").append('<div class="errorMsg draggable"><img class="close" src="../mime/close.png">'+ data + '</div>'); //** here 2nd div
                      }
                        $("#customer").val("");
                        $('#address').val("");
                        $('#phone').val("");
                        $('#initamount').val("");
                    }
                });

            $(".close").button().click(function() {
                $(".close").parent().css("visibility", "hidden");
            });
       });

Answer №1

To handle dynamically added elements, it is essential to make use of event delegation

$('#SystemMessages').on('click','.close',function(){
    $(this).parent().css("visibility", "hidden");
}); 

Learn more about event delegation here ---> https://learn.jquery.com/events/event-delegation/

Answer №2

Adding the .close element dynamically to your HTML requires you to use the on event handler for proper delegation.


$(".close").button();
$("#SystemMessages").on('click', ".close", function() {
    $(".close").parent().css("visibility", "hidden");
});

Answer №3

To implement the desired functionality, you can utilize the provided code snippet:

$('.close').on('click',function(){
  $(this).parent().hide();
 });

If you encounter any issues, feel free to reach out for assistance.

Note that the .live() method has been deprecated in jQuery version 1.7 and removed in version 1.9. In its place, you can employ the .on() method as demonstrated below:

$(document).on('click','.close',function(){
  $(this).parent().hide();
 });

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

Moving the Anchor of Material UI's MultiSelect Popup on Selection

After updating from Material UI 4.2.0 to 4.9.10, I observed a change in behavior that seems to have originated in version 4.8.3. When using a Select element with the multiple attribute, I noticed that the popup menu shifts after selecting the first item. ...

Node/Express unexpectedly returning string instead of Array after parsing JSON file

Having difficulty parsing an empty (stringified) Array from a JSON file. Instead of returning an empty array, I am receiving a string. The initial set up of my JSON file is: "[]" I am storing the parsed data in a variable using File System let parsedOb ...

Redis VS RabbitMQ: A Comparison of Publish/Subscribe Reliable Messaging

Context I am working on a publish/subscribe application where messages are sent from a publisher to a consumer. The publisher and consumer are located on separate machines, and there may be occasional breaks in the connection between them. Goal The obj ...

Console.log() will not display any JSON duplicates

My JSON data structure is pretty flat and can have duplicate attributes. I built a logic to remove the duplicates but when testing it out, something strange happened. The logic was always counting the attributes once, resulting in no duplicates. To test th ...

Tips for swapping a component with another component in React.js without the need for a page refresh

class Navigation extends Component { constructor(props) { super(props); this.state = { width: window.innerWidth, } } updateWidth = () => { if (this.state.width > 700) { this.setStat ...

Combining Two Dropdown Selections to Create a Unique Name using Angular

I am facing a challenge with 2 dropdown values and input fields, where I want to combine the selected values from the dropdowns into the input field. Below is the HTML code snippet: <div class="form-group"> <label>{{l("RoomType")}}</labe ...

I need assistance with an issue on my Google Dev Console, as it keeps showing an error stating that ".getcontext is

Looking for some assistance here as my development console keeps displaying an error: Uncaught TypeError: canvas.getContext is not a function. Here is the problematic code snippet: `var canvas = document.createElement; var c = canvas.getContext("2d&qu ...

Can you tell me about the feature called "Inspect Browser" box?

Can you identify the significance of this enigmatic purple box while inspecting elements in the browser's developer tools? It does not correspond to padding, margins, or borders, yet it seems to be occupying space within the designated div. [1]: http ...

The component "react-native-snap-carousel" is having trouble displaying the card image

Recently, I started working with react native and encountered an issue while trying to implement the "react-native-snap-carousel". The carousel was functioning correctly with the data provided in the "carouselItems" array, but I faced difficulties with dis ...

Is it conceivable that Rails may be rendering HTML at a slower rate compared to static

When using a Rails layout, you can include HTML tags to render images like this: <%= image_tag("logo.png", :alt => "Sample App", :class => "round") %> This will generate the following HTML code: <img alt="Sample App" class="round" src="/i ...

Tips for ensuring consistent alignment of the final navigation item

I'm having trouble understanding why the layout collapses when I resize the window horizontally. I've attempted to adjust the width of the div and tried using display:block. My website is built with Bootstrap 3, although I don't believe that ...

Arranging progress bars between various nodes using HTML and CSS

I am currently facing a challenge in creating a stepping wizard form layout that features a bar at the top of the page. This bar displays a dynamic number of steps (nodes) and progress bars that connect these nodes. However, I am encountering difficulties ...

ways to invoke javascript function on body loading

I'm struggling to invoke a JavaScript function when the body loads. Currently, I have the function call on a button but cannot get it to work when added to the body load event. HTML: <body onload="bodyload();"> JavaScript: function bodyload( ...

Changing the background color using jQuery when an element is focused and when it loses

Currently, I am facing an issue with a form that includes three text input fields. My goal is to change the background-color when one of these fields has focus, and then set it back to its original color once it loses focus. Below is the code I have come u ...

Clicking on the background does not alter the onclick function

Can anyone help me troubleshoot my code? My function load() isn't changing the background of .firstDiv for some reason. I've checked multiple times but I can't seem to spot any errors. function load() { document.getElementsBy ...

Using JQuery to fill an HTML dropdown menu with data from a JSON file

I've been struggling with this issue for a while and despite reading through other posts, I still can't seem to get it to work. My problem lies in populating a drop down menu with JSON data. Although the drop down menu appears on my HTML page, i ...

Monitoring changes to a SCSS file

I'm feeling completely baffled. I've put in my best effort to resolve this issue. The problem lies with my SCSS file and its watcher that doesn't appear to be functioning properly. A regular CSS file is not being generated at all. Here&apos ...

When using Selenium to locate an element, it appears to be returning an unexpected empty object

This question has been bothering me for quite some time. I am currently using Selenium in conjunction with Python to find an element within a webpage. The specific element I am targeting is as follows: <a id="topmenu_adhocQtraditional_Reports" ...

An example of text that includes a link using ES6 template strings

My goal is to display the message "I read and agree to the privacy policy.privacy policy." where the 'privacy policy' part is a clickable link. I attempted the following code but it resulted in "I read and agree to the [object object]." const p ...

Transferring documents using JavaScript

I have been using the following method to upload files to my Laravel backend: setFile(id, e) { let self = this; let reader = new FileReader(); reader.readAsDataURL(e.target.files[0]); reader. ...