Retrieving information from dynamically generated list items

I am trying to retrieve the value from a dynamically created LI element.

After some research, I came across this helpful answer that explains how to achieve it in a normal scenario.

The following code is working perfectly for the two existing elements within my LI:

<ul class="nav nav-pills nav-stacked" id="listPreReq" style="height: 200px; overflow: auto" role="menu">
  <li class="active"><a href="#">Action</a></li>
  <li><a href="#">Another action</a></li>
</ul>


$("#listPreReq li").click(function() {    
 alert($(this).html());  
});

However, when I try to add more elements to the LI dynamically, those new elements do not trigger the $("#listPreReq li").click event. I'm unsure about the reason behind this behavior. You can check out a live demo here.

$('#btPre').click(function(e) {
  var Psize= $("#listPreReq").find("li");
  Psize = Psize.size()+1;
  $("#listPreReq").append('<li><a href="#">Page '+Psize+'</a></li>');
});

Answer №1

View Solution Demo

Instead of attaching events to the document, you can also attach them to the ul element:

$("#listPreReq").on('click', 'li', function() {    
    alert($(this).html());  
});

For more information on this topic, check out event delegation.

Answer №2

Instead of using

$('#btPre').click(function(e) {...
, try using
$(document).on('click','#btPre',function(e) {...
. This technique, known as event delegation, will ensure that it is fired!

UPDATE: You should also update this part:

$("#listPreReq li").click(function() {...

Replace it with:

$(document).on('click',"#listPreReq li",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

Displaying images based on certain conditions being fulfilled in Laravel

As a beginner in Laravel, I am working on creating a dashboard. My goal is to display an image of a checkmark if the lastdatasync (timestamp data type) records are within the last 24 hours. If it's been more than 24 hours (such as last week), then I w ...

Utilizing CSS naming conventions to bring order to class inheritance

I'm a bit unclear about the rationale behind using this specific CSS structure: h2.class-name It seems like you could simply use .class-name and apply that class to the h2 element: <h2 class="class-name">Title thing</h2> Unless it&apos ...

Methods for enlarging a sub-element without any impact on its encompassing parent element

I need the child class to not affect the overflow of the parent when I hover over it. My initial thought was to remove the line position: relative; from the parent, but this solution does not work properly when dealing with multiple nested positions. .p ...

Troubles encountered with adapting apexcharts size within a react environment

As a novice front-end coder transitioning from a data analyst background, I am currently facing an issue with integrating an ApexChart visual into a flexbox element. The visual appears fine at a resolution of 2560x1440 pixels. However, upon further resizin ...

Implementing a recurring interval for a timer

Currently, I am attempting to create a stopwatch using the following code: var min = 0, sec = 0, censec = 0 $("#startBtn").on("click", function() {// upon clicking start button $(this).hide();// hide start button $("#stopBtn").show();// show stop butto ...

"Short-term" variation not appearing within the Material-ui Drawer component

I am attempting to create a responsive drawer component using material-ui, where it is toggleable on smaller screens and remains open on desktop. Following the mui documentation, I added the temporary variant to the drawer, but it does not display in desk ...

When attempting to send data to the ServiceStack RESTful service, an error message of 'Access is denied' was received

I created a RESTful service using ServiceStack to send data to a database. It worked perfectly when tested locally. However, after deploying it to a server and running the same jQuery $.ajax call code, I encountered an 'Access is denied' error. I ...

Retrieving JSON data from a PHP file through a standalone JavaScript script

I am in need of creating a JavaScript file that will assign values to two variables within a PHP file. The PHP file should then construct a JSON structure and display some data. My goal is to have a form written in JavaScript with two input fields that wi ...

Adjust the HTML 5 range slider to update according to the selected value

Is it possible to create a custom marker on an HTML5 range input element? I'm looking for a way to change the design of the circle marker as it moves along the scale from 1 to 10. Specifically, I want to change the color of the marker based on its po ...

Arrange list items in a circular pattern

Is there a way to achieve the desired appearance for my navbar like this link? I have tried rotating the text, but the vertical text ends up too far from the horizontal. Any suggestions? .vertical { float:right; writing-mode:tb-rl;/*IE*/ w ...

Error: Attempting to assign a value to the 'fillStyle' property of a null object in HTML5 Javascript

I've been experimenting with HTML5 canvas and JavaScript to draw shapes. While I can successfully draw shapes directly within the HTML file, I encounter an Uncaught Type Error when attempting to do so through an external JavaScript file. My goal is si ...

Create a custom horizontal scrolling feature for a list of images inside a div

Just starting out with react and I have an array of image URLs. My current output looks like this: Output Image Link: Looking to remove the scroll bar at the bottom and get rid of scrolls entirely. Here's how I want it to look: Expected Output: Wa ...

When the button is clicked, the div will fade out and then fade back in

I am looking to create a one-page website where clicking a button will fade in the impressum-div, and another click on the same button will fade out the impressum-div. Currently, I have successfully managed to fadeIn the div on click. However, when I try ...

ways to incorporate the textarea ID within a jQuery function

In the web form I'm working on, there is a Textarea and a link button that triggers a popup message showing the cursor position if it's placed in the text area. However, the code below isn't displaying anything: <textarea id="msgtxt" run ...

What is the recommended sequence for adding AngularJS to the index page?

I am new to AngularJS and currently working on a project where I need to include multiple JavaScript files in my index.html page. After doing some research, I came across a post on Stack Overflow that mentioned the importance of including the angular.js fi ...

Deactivate the next button on the paginator within the PrimeNG p-table

In the p-table paginator, I want to disable the next button when a specific boolean is set to false. Below is my p-table setup: <p-table #dt id="{{id}}_table" [(value)]="_datasrc" [columns]="cols" [rows]="rowNumber || ...

I selected a single radio button and stored a boolean value (e.g. 1) in the database

I've designed an online exam system where I input questions and various options, as seen in the screenshot below: https://i.sstatic.net/pyCgN.jpg Regarding my questions: I input a question (such as 1+1= ?) and its corresponding options shown in the ...

Creating a dynamic grid layout using div elements and CSS/Bootstrap

https://i.sstatic.net/o9wmq.png Looking to achieve a design like this using either pure CSS or Bootstrap. The goal is to have each button be a fixed size and arranged in a list format without specifying exact row or column lengths. For example: <div c ...

Firebase firestore is reporting an error stating that the requested document cannot be found

Using nodejs, I am working on creating firestore documents in a specific structure that includes the collection name followed by an ID and then the document itself. While my code successfully adds the document, it does not create the parent document (ID) i ...

The DIV container refuses to line up properly

Despite my best efforts, I have not been able to align these 4 boxes properly after going through documentation, tutorials, and examples. div#frontpage{width:100%; } div#1{width:25%; float:left; position:relative;} div#2{width:25%; float:left; position:re ...