2

I'm creating dynamic elements using jquery and try to bind listener for elements. by binding listener using

$('#div11').on('click',$('#textbox31'),function(e){showPopupImage(e);});
$('#div11').on('click',$('#textbox32'),function(e){alert('hi');});

function,it adds listener to descendents even though i specify the particular field to bind.

pls,suggest me the good way to handle my situation.

codingrose
  • 15,563
  • 11
  • 39
  • 58
PravinKumar.R
  • 335
  • 1
  • 3
  • 15
  • Try this [Link](http://stackoverflow.com/questions/2463487/jquery-listener-doesnt-listen-to-events-on-dom-elements-dynamically-created) – Govinda Rajbhar Jan 13 '14 at 11:40
  • Using jquery ! Then why you tagged javaScript? – Voonic Jan 13 '14 at 11:44
  • @shadow: The javascript tag is valid, JQuery is a javascript library – musefan Jan 13 '14 at 11:47
  • @musefan But its a library, not native javascript – Voonic Jan 13 '14 at 11:48
  • @shadow: JQuery is written in javascript, and to use it you must write javascript. The code included in the question is all javascript, so it makes sense to tag it as so – musefan Jan 13 '14 at 11:54
  • @musefan In title you explicitly specify that you only want jqueries – Voonic Jan 13 '14 at 11:56
  • @shadow: I didn't write the title, I am not the OP. Besides the OP is NOT stating they only want JQuery solutions, they are stating that they are using the JQuery library, so naturally you would provide a JQuery solution. But it is still ALL javascript anyway. SO allows multiple tags for a reason, and it is very common place for the language to be one of them - regardless of any libraries that may or may not be used – musefan Jan 13 '14 at 11:59

2 Answers2

3

The problem is that you are not specifying the correct parameters to the on function. If you look at the JQuery documentation, you are using the following function overload:

.on( events [, selector ] [, data ] )

The part you are specifying incorrectly is the selector parameter. This parameter requires a selector string, not a JQuery objct.

The following will work:

$('#div11').on('click','#textbox31',function(e){showPopupImage(e);});
$('#div11').on('click','#textbox32',function(e){alert('hi');});

Notice I have replaced $('#textbox31') with '#textbox31'.

Here is a working example, you will see that the click event is not applied to textbox33 and textbox34

musefan
  • 47,875
  • 21
  • 135
  • 185
1

Try it :

$('#div11').on('click', '#textbox31',function(e){
        showPopupImage(e);
});
$('#div11').on('click', '#textbox32', function(e) {
  //do something
});

Using .on() you can define you function once, and it will execute for any dynamically added elements.

Govinda Rajbhar
  • 2,926
  • 6
  • 37
  • 62