"Troubleshooting: Issues with jQuery's .on method when used with dynamically added

I have a large number of

<button class="lb">
  <div class="l"></div>
  <div class="c">2</div>
  <div class="r"></div>
</button>

Some of these buttons are present in the initial DOM when the page loads, while others are dynamically added using JavaScript.

Upon clicking on any button, I want the value inside the "c" div to increase by 1.

I attempted to achieve this with the following code:

$(".lb").on("click", function(event) {
  $('.c', this).html(parseInt($('.c', this).html()) + 1);
  $(this).unbind('mouseout');
});

However, this only works for the elements loaded during pageload and not for those inserted via JavaScript afterward.

I am unable to pinpoint the issue and would appreciate any guidance.

Thank you! Raphael

Answer №1

Implement event delegation to the parent of .lb or even to the document itself. As mentioned by @Zolton Toth, make sure to use off instead of the deprecated unbind.

$(document).on("click", ".lb", function(event) {
  $('.c', this).html(parseInt($('.c', this).html()) + 1);
  $(this).off('mouseout');
});

Answer №2

There are a few key points to remember when utilizing the .on() method as a delegate:

$(' --CONTEXT-- ').on('click', ' -- YOUR ELEMENT -- ', function () {

});

// Similarly, to remove this event using the new approach
// you would use .off()
$(' --CONTEXT-- ').off('click', '-- YOUR ELEMENT --');

For example:

$(document).on('click', '.lb', function () { });

However, setting the context to document can be too broad. It is recommended to use a closer parent element that encompasses where this element may appear for better performance.

$('#someParent').on('click', '.lb', function () { });

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

Can switching to polling data from a SQL database instead of a file in a chat application lead to improved performance?

Currently developing a chat application and considering using a SQL database for it. The challenge is that I've come across conflicting information online regarding the performance of using a DB versus a regular file (such as Text or JSON). User expe ...

Confirm the presence of Cookie and save the data

I'm a beginner in the world of Javascript and Ajax, attempting to save a user's name using cookies. I have created a form where users can input their first name (identified by id = firstName). My goal is to remember this information so that the n ...

Cease / Cancel Ajax request without activating an error signal

I am looking for a way to intercept all ajax requests on a page and stop/abort some of the requests based on certain criteria. Although initially using jqXHR.abort(); worked, it caused the error event of all the aborted requests to be triggered, which is n ...

How can I effectively run and execute JavaScript received from a Node server using Node.js?

Hey everyone, I'm just starting out with Node and I've run into a little issue that I could use some help with. Basically, I have a page at that does some stuff, and I want to connect to the node server which is located at . var server = requir ...

If the value is not set for $_POST when sent via an AJAX request

I have set up a zii.widgets.jui.CJuiDialog to send a form via ajax to my controller. However, I am facing an issue where the post variable if(isset($_POST['Item'])) does not seem to be present when I test for it in the controller. I am trying to ...

Repeating X and Y Axis Labels on Highcharts

Highchart is new to me. I recently created a basic chart showing the count of males and females over the past five years. I have included a screenshot for reference. I am wondering if it's possible to remove duplicate labels from both axes? Below is ...

Guide to dynamically insert rows in HTML using Vue.js based on the selected option

This is the initial row. Depending on the selection made here, different rows will be displayed <div class="row"> <div class="col-md-4"> <div class="form-group label-floating"> <label class="control-label">Case Type< ...

"Retrieve data from an Excel file and either present it in a textarea or store it as an array

Is it possible to use JavaScript to read an Excel file and convert a single column (identified by name or index) into an array in JavaScript? ...

How do I access additional data when a selection is made in an HTML option selector that has JSON data added?

I need help with my code and understanding the terminology, here is what I have: var json = "https://example.com/"; $.getJSON(json,function(data) { for (var x = 0; x < data.length; x++) { $('#select').append( '& ...

Using the jQuery AJAX function to modify the URL query string

I currently find myself on a webpage Is there a way to add a URL query string without reloading the page? For example, when I click a button, can the URL change to using jQuery ajax functions? ...

Using jQuery in CodeIgniter to create a dynamic dropdown list that is dependent

After successfully implementing a working dropdown dependent form, I encountered an issue where hidden input fields within the hidden div were still submitting post values. Is there a way to prevent hidden inputs from being submitted when their parent div ...

Unable to sign up for WordPress function

I'm having trouble getting my function registered properly in WordPress, no matter how many times I try. So far, here's what I've done: Inserted code into themes functions.php function test_my_script() { wp_register_script( 'custom-s ...

Is it possible to return PHP parser errors as JSON data?

I am facing an issue with my HTML page that uses a JQuery Ajax call to communicate with a PHP page and expects a JSON response. If the PHP encounters a parser error, it sends back the error message but not in the expected JSON format. This leads to a "JSON ...

Verify the MAC address as the user types

I need to verify a form field for MAC Addresses and have implemented the following code that does the job. $('body').on('keyup', '#macAddess', function(e){ var e = $(this).val(); var r = /([a-f0-9]{2})([a-f0-9]{2})/i, ...

Having trouble storing radio buttons and checkboxes in MySQL database using AJAX

My app is facing an issue where radio buttons and checkboxes are not correctly entering information into the database. Currently, only text fields are successfully saving data, while checkboxes and radio buttons are only recording the value of the first ra ...

Sending dynamic boolean model property via AJAX dynamically

I am facing an issue while passing a property from my model to an AJAX form. The boolean value is resolving as "true/false" and causing problems in the process. $.ajax({ url: '/Projects/SearchTable2', type: "GET", data: { sub ...

Stopping errors are a common occurrence in synchronous AJAX

I recently encountered an issue with my AJAX request setup. In the success callback function, I called a new function to render Google links and made another AJAX call. To address some performance concerns, I attempted to change these asynchronous calls t ...

Tips for sending JSON data to the line chart function

Creating a line chart using Highcharts involves retrieving values from a database and passing those values to the line chart. Here is an example: //categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun ...

After the URL of the window was updated, the local storage was automatically cleared

function makeAjaxCall(){ ............... ............... success:function(response){ localStorage.setItem("token", response['token']) window.location.href="https://www.example.com/profiler/" } } The code snippet above is fo ...

Is there a way to switch between showing and hiding all images rather than just hiding them one by one?

Is there a way I can modify my code to create a button that toggles between hiding and showing all images (under the user_upload class), instead of just hiding them? function hidei(id) { $('.user_upload').toggle(); Any suggestions would be grea ...