0

I am trying to use on a dynamically added content and I'm not sure what I'm missing. I have two buttons one creates UL inside DIV. Then I click on another button to create LI inside the UL. On click on any of the LI i should get an alert message but nothing is happening!

http://jsfiddle.net/EkW63/

<div id='ok'></div>
<button id='fst'>create ul</button>
<button id='snd'>create li</button>

<script>
$("#fst").click(function(){
    $("#ok").html("<ul class='ul'></ul>");
});
$("#snd").click(function(){
    $(".ul").html("<li class='myclass'>one</li><li class='myclass'>two</li>");
});

$("ul").on('click', 'li.myclass', function(){ alert('ok'); });`
</script>

any suggestion?

1
  • 1
    ul itself is created dynamically, that means it doesn't even exist when you tried to call on on it. Commented Jul 22, 2013 at 2:30

3 Answers 3

2

You should bind on with #ok div. Like this:

$("#ok").on('click', 'li.myclass', function(){ alert('ok'); });

Your ul is dynamically created as well so it will not work. on should be bound to elements that are already on the page when it loads.

Sign up to request clarification or add additional context in comments.

Comments

1

Use like this

$(document).on('click', 'ul li.myclass', function(){ 
    alert('ok'); 
});

Or even better ( opinion )

$("#fst").click(function(){
    $("#ok").html("<ul class='ul'></ul>");
});

var li = $("<li class='myclass'>one</li><li class='myclass'>two</li>");
$("#snd").click(function(){
    $(".ul").html(li);
});

li.on('click', function() {
   alert('hi');
});

For overall better code write all of like similar to this

$("#fst").click(function(){
    $("#ok").html('').append(
        $('<ul>', {'class': 'ul'})
    );
});

var li = $('<li>', {
    'class': 'myClass', 
    click: function() {
        alert('Hello');
    }
}),

$("#snd").click(function(){
    $(".ul").html('').append(li);
});

I use append because it's quicker, than innerHTML

Comments

0

Since you're dynamically creating the element, you need to bind the click event to the new element right after you created it, otherwise it won't work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.