0

I want to create <li> in existing <ul>. I succed to make that. But I want to make onclick() function on <li> who was created. But nothing happens when I want to call my JavaScript method.

I think <li> doesn't exist when I load my browser page and when <li> are create the browser doesn't find <li> who was created.

Method JavaScript to create <li> in <ul> :

 $('#myList').click(function () {
 $("#firstYear ul").append('<li><a href="">' + valueArray + '</a></li>');
     });

Method OnClick on <li> who was create but nothing happens :

 $('#firstYear ul li').click(function () {
    console.log('Ok');
         });

If you have some solutions :)

Thank's

Hizu'
  • 21
  • 5
  • where exactly are you doing the click on `li` assignment, i.e. the second example of your code? because it should be done **after** you append the `li` – Ovidiu Dolha May 30 '17 at 07:00
  • 1
    It is because the `li` is created dynamically. Use `$('#firstYear ul li').on('click', '#firstYear ul li', function() {});` – Marnix Harderwijk May 30 '17 at 07:02

5 Answers5

0

You can use the .on() method:

$('body').on('click', '#firstYear ul li', function() {
   console.log('Ok');
});

This will work also for dynamically added elements.

amhev
  • 313
  • 1
  • 3
  • 12
0

Make sure the click event you register is done after you have the element (i.e. after the append):

 $('#myList').click(function () {
    $("#firstYear ul").append('<li><a href="">' + valueArray + '</a></li>');
    $('#firstYear ul li').click(function () {
        console.log('Ok');
    });
 });
Ovidiu Dolha
  • 5,335
  • 1
  • 21
  • 30
0

Create a function and call that function when clicking on existing li and newly added li

function logResult () {
  console.log("ok");
}

Add onClick method in you li

$("#firstYear ul").append('<li><a href="" onClick="logResult()">' + valueArray + '</a></li>');
 });

And in your click function also call logResult

 $('#firstYear ul li').click(function () {
   logResult()
 });
Syam Pillai
  • 4,967
  • 2
  • 26
  • 42
0

I would personally use delegate method jQuery provides to write down method only once and then reuse it

$(document).ready(function() {
  $('#list').delegate('li','click', react);
  $('#list').append('<li>hello</li>');
  $('#list').append('<li>hi</li>');
})


function react() {
  alert($(this).text());
}

here is working example https://codepen.io/kejt/pen/eWwRBG

Kasia
  • 1,665
  • 1
  • 10
  • 16
0

This is happening because your list is getting generated after your page has been loaded in the browser, due to this, click event not able to find the element which are created dynamically.

What you have to do is, you have trigger click event on the document object inside the browser. For example,

$(document).on('click', '#firstYear ul li', function() {
  console.log('Ok');
});

You can also refer to this also for more info Event binding on dynamic created element

Nerdy Sid
  • 332
  • 5
  • 14