The Jquery function for selecting a div added by an Ajax call is not functioning properly, but it works fine without the need for an

I have a unique checkbox that I created using an Ajax call. The issue I'm facing is that the jQuery to select the checked input in the second div #test_checkbox_ajax isn't working, while it works perfectly fine in the first div #test_checkbox. Creating the div with Ajax call is essential for my code to function properly. How can I resolve this problem? Any assistance would be greatly appreciated. If you know of any similar questions, please let me know so I can find a solution. Thank you in advance.

$(window).load(function() {
  $.when(loadProfile()).done(function(res){
    addProfile(res);
  }).fail(function(resp) {
    if(resp.status!=408) {
      //error
    } else {
      //other
    }
  });
});

$(document).ready(function() {
  $('#test_checkbox input').on('click', function() {  //this works perfectly
    console.log('enter');
    if ($(this).is(":checked")) {
      alert('checked');
    } else {
      alert('not checked');
    }
  });
  
  $('#test_checkbox_ajax input').on('click', function() { //this is not working, why??
    console.log('enter');
    if ($(this).is(":checked")) {
      alert('checked');
    } else {
      alert('not checked');
    }
  });
});

function loadProfile() {
  return $.ajax({
    type: "POST",
    url: "GESINTRANET",
    data: "TPMAP=INSEGN"
  });
}

function addProfile(res) {
  $('#test_checkbox_ajax').empty();
  $('#test_checkbox_ajax').append('<label class="custom_single_label">Area</label>');
  $.each(res.aree, function(i, area) {
    $('#test_checkbox_ajax').append('<label class="custom_single_checkbox_container">' + area.nome + '<input type="checkbox" class="custom_checkbox" value="' + area.id + '"><span class="custom_checkbox_span"></span></label>');
  });
}
/* custom input type: checkbox */

div.custom_checkbox_container {
  padding: 15px 20px;
  width: 100%;
  position: relative !important;
  top: 0 !important;
  left: 0 !important;
}

div.custom_checkbox_container label.custom_single_label {
  font-size: 16px;
  font-family: 'Roboto', sans-serif;
  color: #222222;
  margin: 0;
}

... (additional CSS code here)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom_checkbox_container" id="test_checkbox">
  <label class="custom_single_label">Vehicle</label>
  <label class="custom_single_checkbox_container">Bike
    <input type="checkbox" class="custom_checkbox" value="bike">
    <span class="custom_checkbox_span"></span>
  </label>
  <label class="custom_single_checkbox_container">Car
    <input type="checkbox" class="custom_checkbox" value="car">
    <span class="custom_checkbox_span"></span>
  </label>
</div>
<div class="custom_checkbox_container" id="test_checkbox_ajax">
</div>

Warm Regards, Amila Fernando

Answer №1

Make sure to connect your event handler to the document or a suitable parent element that isn't impacted by ajax updates. Check out the Delegated event handlers section on on() documentation page for reference.
For instance, adjust

$('#test_checkbox input').on('click', function() {  //this work perfectly
    console.log('enter');
    if ($(this).is(":checked")) {
      alert('checked');
    } else {
      alert('not checked');
    }
  });

to

$(document).on('click','#test_checkbox input', function() {  //this work perfectly
    console.log('enter');
    if ($(this).is(":checked")) {
      alert('checked');
    } else {
      alert('not checked');
    }
  });

Update:
Based on @WernerPotgieter's recommendation, attach the listener to document instead of body. While I've provided an example with the event listener connected to the document, it's advised to minimize the use of document or body for delegated events in large documents. Instead, position the listener as close as possible to the target element for optimal performance.

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

The POST request in Node.js using Express is returning an undefined value

Having an issue with Node.js + express on the backend while trying to parse the body of a simple POST-request. The server console is showing "undefined" as the result. Tried various options from StackOverflow without success, even after including body-par ...

Customize Material UI components by incorporating SASS classes

Currently, I am using Material UI components but I want to streamline my styles by moving them all into a .scss file. Right now, I have a significant styles object within the same JavaScript file where I am utilizing the Material UI components. This styles ...

Unusual naming problem encountered in DataTables when employing diverse functions

I'm encountering an unusual issue with DataTables. In the documentation, there is inconsistency in using either a capital D or lowercase d when referring to the class name: var table = $('#example').DataTable(); Sometimes it's like th ...

Obtain the option tag's name

One of my challenges is working with a dynamically created dropdown in HTML and having a dictionary in the back-end to retrieve keys. As users keep adding options to the dropdown, I face the issue of not having a value attribute like this: <option valu ...

Retrieve information from a JSON script using C#

I need to extract data from a homepage, but the information I'm looking for is embedded in a JSON script. How can I retrieve this value? For example: <div id="contentWrap"> <div id="contentTextWrap"> <div id="contentText ...

I am looking to showcase a text directly from the properties file using the thymeleaf template engine

I have two files named message_ar.properties and messages_fr.properties for internationalization purposes. Within my HTML file, I am attempting to show the correct label for a confirm message. To accomplish this, I am utilizing Thymeleaf as my template e ...

What could be causing the AJAX http_response_code() to return an incorrect value in this PHP include file? Is it possible that the trailing space at the end is

This issue is perplexing - a seemingly innocuous blank line at the end of a required PHP file in an AJAX POST endpoint, named cursed.php, is causing HTTP response code 500 to fail. Strangely enough, with the blank line present, the status code returned is ...

Is there a bug in Firefox concerning the accuracy of document.body.getBoundingClientRect().top?

When I access Firefox version 17.0.1 and request document.body.getBoundingClientRect().top; on a simple site with no CSS styling applied, it returns an incorrect value. Instead of the expected 8, which is the default for the browser, it shows 21.4. However ...

Jquery submenu accordion toggles open and closed with each click

My website has a hamburger menu with an accordion-style submenu implemented using jQuery for devices 1084px and smaller. For larger devices, the menu utilizes a hover-style submenu on desktop. However, I encountered issues when trying to use both the hove ...

Convert HTML to JSON using a selection

After selecting multiple values in the alpaca form using a select ui element, I encounter an issue when saving the form. When I use JSON.stringify(val) to generate the JSON data, it only includes the ids of the selected elements. However, I would like the ...

Uncover the hidden message in a string encoded for JavaScript

This encoded HTML code is intended for use in a JavaScript function <div class=\"ProductDetail\"><div style=\"width:780px\">\r\n\t<div class=\"baslik\" style=\"margin: 0px; padding: 5px 10px ...

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...

Transmit information from a JavaScript AJAX function to a JSP page

My current goal involves a user clicking on a link on the home page, let's say /home.jsp. Upon clicking this link, I extract the value and use it to call a RESTful resource that interacts with a database and returns a response. The communication with ...

Is there a way to prevent cards in a carousel slide from wrapping onto two lines?

Currently, I am utilizing Bootstrap 5 to develop a website and an accompanying carousel. My objective is to align all the items in the carousel vertically. Unfortunately, I am encountering some difficulties in achieving this layout. Can anyone provide assi ...

What is the best way to transmit a JSON object from a Python code to jQuery?

After searching through various APIs and resources, I'm still struggling to properly fetch a JSON object from a Python script using AJAX. It seems like the issue lies in how I am handling the JSON object. To begin, I have a python script on my server ...

Searching for form fields in Wordpress using custom post types

Currently, we have a dropdown option that automatically populates from custom post types and displays for the customer to choose from. However, the list has become extremely long, so they would like the functionality of being able to start typing a company ...

Using Python and Selenium to retrieve information from the attribute 'data-label'

https://i.stack.imgur.com/zb7f5.jpg try: details = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "DataTables_Table_5")) ) scores_list = details.find_elements_by_tag_name('tbody') for sco ...

Tips for Positioning a Page Layout in the Center Using HTML and CSS

I'm a beginner in HTML and CSS and I'm trying to create a simple webpage layout from scratch. I want all the elements of the page (nav, header, section, footer, etc.) to be centered while still keeping the nav bar on the left side. I've set ...

Sending arguments to child components within KnockoutPassing parameters to child components in

My coding setup includes the following template: <template id="item-list"> <form action="" data-bind="submit: addItem"> <input type="text" name="addItem" data-bind="value: newItem"> <button type="submit">Add Item</butt ...

Ways to adjust the border color when error helper text is displayed on a TextField

I am currently working with React Material UI's TextField element. What I aim to achieve is when the submit button is pressed, the helpertext displayed should be "Please enter the password." It should look like this: https://i.sstatic.net/Nu0ua.png ...