0

This is a java file which generates a div & a text box dynamically.

js file

var count = 6;
$(document).ready(function(){
    $("#addmoreParam").click(function(){
        $("#showParam tr:last").before("<tr><td><div style=\"width:150px;background-color:#FFF; height:20px;\" contenteditable=\"true\" class=\"paramDiv\" id="+count+"></div></td><td><input type=text name=\"paramValue" + count +"\" class=paramValue /></td></tr>");
        count++;
    });
});

Below is the code which produces alert when writing anything to div. I tried hard bu it is not giving alert box.

$(function(){
    $(".paramDiv").on('keyup', '.paramDiv', function(){
        alert('dd');
    });
});

I am using jquery-1.9.1.js. Is on supported in this jquery version ?

Harshit
  • 5,147
  • 9
  • 46
  • 93

1 Answers1

3

As per event delegation:

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future. Inside the Event Handling Function.

Issue with your code is, you haven't attached event to element which exists now and in future. like #showParam. Use

$('#showParam').on('keyup', '.paramDiv', function(){ 
      alert('dd');
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • 1
    If this should work then why not closing as Dupe instead of answering. This is very common problem to answer repeatedly. Please close such **obvious** dupes rather than answering. – Tushar Mar 17 '16 at 08:51
  • 1
    @Tushar: OP has used the concept of delegation. and there is wrong approach used, which is pointed out here. – Milind Anantwar Mar 17 '16 at 08:53
  • The concept of delegation is well explained in post. If the post answers the question even if indirectly, it can be used as dupe target. [OP also accepts that this is dupe(_indirectly_)](http://stackoverflow.com/questions/36055335/jquery-keyup-dynamically-generated-div#comment59758618_36055335) – Tushar Mar 17 '16 at 08:59