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.

7
  • Try this Link Commented Jan 13, 2014 at 11:40
  • Using jquery ! Then why you tagged javaScript? Commented Jan 13, 2014 at 11:44
  • @shadow: The javascript tag is valid, JQuery is a javascript library Commented Jan 13, 2014 at 11:47
  • @musefan But its a library, not native javascript Commented Jan 13, 2014 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 Commented Jan 13, 2014 at 11:54

2 Answers 2

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

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

Comments

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.

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.