Repeated trigger of click events on dynamically created divs

When making an Ajax call, I dynamically generate a div and create a click action associated with it. I give the div a unique ID based on a key value from the data. The problem arises when the same key value is received in subsequent Ajax calls.

var $orderData = $('<div><table width="100%"><tr><td nowrap width="15%">'+valX1
                + '</td><td width="10%" class="imgClass" ><img src=' 
                + imgPath + ' id="img_'+serId+'" /></td> 
                + <td nowrap width="25%">' + customerName 
                + '</td><td nowrap width="25%">' + orderPendingCount 
                + '</td><td nowrap width="25%">' 
                + plant+'</td></tr>' + '<tr><td nowrap width="15%">' + modelName 
                + '</td><td></td><td nowrap width="25%">' 
                + totalNo + '</td><td nowrap width="25%">' 
                + deliveredTotal+'</td><td nowrap width="25%">'
                + salesPersonName + '</td></tr></table></div>'  );


$('body').on('click', '#img_'+serId, function(){
    $('body').css('cursor', 'default');
    alert(serId);
    return false;
});

The click action is triggered correctly, but problems arise when the same serId is used in multiple Ajax calls. The click action is created again for the div, resulting in repeated calls.

Is there a way to clear the div action script and div before creating it again?

Answer №1

It is recommended to utilize a class for this purpose. By applying the class to an element, it will automatically inherit the specified event. Here's an example:

$('body').on('click', '.divImgClass', function(){
    $('body').css('cursor', 'default');
    alert(serId);
    return false;
});

By doing this, you can avoid the need to constantly reset the event as it will already be assigned to any element with that class.

Answer №2

Be sure to add the script prior to regenerating the div and test it out:

if($('#newdiv').length != 0) {
  $('#newdiv').delete();
}

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

Operating two independent Angular applications simultaneously on a single webpage

I'm currently developing an application that allows multiple Angular applications to be embedded within a main frame. Currently, I am using IFrames for this purpose, which is functioning well but has its limitations. I am exploring ways to embed ano ...

What is the JavaScript mouseenter/out event all about?

My goal is to create a hover effect using JavaScript. I am utilizing the mouseenter and mouseout events to display the content when the mouse hovers over a button and remove the content when the mouse moves out. However, I am facing an issue where the cont ...

Steps to completely eliminate all elements from an object using specific keys

I have been pondering the most efficient method to delete all elements of an object through an onClick function. The goal is for the handler to remove all elements. Despite attempts with methods like the delete keyword and filtering, clicking the clear all ...

What is the correct way to load a column of images without affecting the readability of the text alongside them? (see image below)

https://i.stack.imgur.com/rBL50.png Whenever my page loads, there is a card with a vertical list of images. Due to the loading time of the images, the text appears first and gets squished as shown in the provided screenshot. Is there a way for the text to ...

What is the best way to verify the accuracy of my model when it includes an array property?

One of the challenges I am facing is dealing with a class that has an array property in MVC. public class MyClass { public int Contrato_Id { get; set; } public string Contrato { get; set; } public int Torre_Id { get; set; } public string T ...

Switching between pages, displaying new content within a div without changing the URL address

I have experience working with the Ajax/jQuery .load() or php include() functions to load additional content into a div on a web page. Please check out this example I've created: my website featuring page transitions The setup for this page involves ...

Is there a way to prevent my jQuery from triggering the <a href> unless the ajax post is successful?

I am attempting to update the database and redirect the user's browser to a new page with just one click. Here is how the HTML appears: <a id='updateLiveProgress' style='width:118px;' href='~link~'>Click here</ ...

Adjust element based on the position of another element (sticky)

Is it possible to rotate a text block so that it remains anchored to the bottom of a red rectangle, even when the rectangle is rotated? Similar to how it works in Figma, but simpler. For example, if I rotate the rectangle by 180 degrees, the text should be ...

The value of a variable undergoes a transformation following its insertion into an

During my coding tests, I came across this snippet of code: <script> var newData = {}, graphs = [] for(var j=0; j<2; j++){ newData["name"] = 'value '+ j console.log(newData["name"]); graphs.push(newData); console.log ...

Form modifications on wicket are no longer present after an ajax update

I am currently working on a rather large and intricate form that includes numerous form components. Within one of the drop down fields, I have implemented an AjaxFormComponentUpdatingBehavior to manage any changes in the dropdown selection. Based on these ...

Playing with Data in AG-Grid using Javascript

I am working on implementing data display using AG Grid with an AJAX call, but I am facing an issue where no data is being shown in the grid. Even though my AJAX call seems to be functioning correctly and returning the desired object List, the grid itsel ...

CSS fails to function properly on websites hosted on nginx servers

During the process of creating a static website, I utilized VS Code and Live Server on my Windows machine. The site appeared to function properly. However, upon transferring the files to my CentOS machine to run the site through nginx, the site loaded cor ...

Tips for utilizing a ForEach loop in JavaScript to create an object with dynamically provided keys and values

Looking to create a JavaScript object with the following structure, where the Car Make and Model Names are provided from other variables. { "Sedan":{ "Jaguar":[ "XF", "XJ" ], "AUDI":[ "A6", ...

Creating a secured page with Node.js and Express: Password Protection

I am a beginner with node.js/express! Currently, I am working on developing a chat site along with a chat admin site. When I navigate to _____:3000/admin, it prompts me for a password through a form. I am looking for a way to verify if the entered passwor ...

Encountering an error message stating that the "@font-face declaration does not adhere to the fontspring bulletproof syntax" while attempting to integrate a custom font

I've been struggling to incorporate a unique font into my website, but I keep encountering the same error every time. Despite my efforts, I haven't found much guidance on how to rectify this issue. Below is the code I'm using: @font-face ...

Aligning text to the right in Bootstrap 5 input fields

I'm trying to align the values of my inputs to the right. Any suggestions on how to achieve this? Here's a visual representation of what I'm looking for. This is the snippet from my code: <td style="text-align:center; vertical-alig ...

JavaScript can be used to open several tabs simultaneously within a single browser window

Looking to open multiple tabs in the main browser? Check out this code snippet: function openSM() { window.open("http://www.google.com","_blank"); window.open("http://www.yahoo.com","_blank"); window.open("http://www.bing.c ...

One way to dynamically retrieve the ID of a jQuery tab using a foreach loop in PHP OOP

I have a category table and subcategory table in my database. Currently, I am attempting to showcase the "category" title as the tab and the corresponding "subcategory" name as the content within the tab. Despite searching for a solution on Google, I was ...

Is there a way to stop a setTimeout function in React before it is triggered?

In my application, I have set up a functionality where pressing a button starts the clock countdown. If no action is taken within 23 seconds (23000), the state changes to "this.state.user". This part is working correctly. However, if you click on the elem ...

Generate a fresh array using a current array comprising of objects

Greetings! I am facing a challenge with an array of objects like the one shown below: const data = [ {day: "Monday", to: "12.00", from: "15.00"}, {day: "Monday", to: "18.00", from: "22.00"}, {day: ...