a developer's notes – a semi-technical web development BLOG

January 29, 2014

Binding Click Events to dynamically added controls with jQuery

Filed under: Javascript / JQuery — Duy Nguyen @ 1:23 pm
Tags: , , , , , , , , , ,

When you dynamically add controls, make sure the container that the controls are added to, has an ID attribute.

Example:

<div id="dynamicCollectionDiv">
           //dynamic controls are added inside this div
</div>

Then you can use jquery to add a ‘click’ delegate on any newly added controls. You used to be able to use the “.live” method but this is now deprecated. Use the “.on” method instead. You must reference the parent container to do the actual binding.

$("#dynamicCollectionDiv").parent().on("click", '.dynamicControlCssClass', function () {
        // do something
    });

Notice the second parameter that specifies a css class called “dynamicControlCssClass.” When you add your dynamic controls, add a css class so you can specify which elements should get the click event delegate. All of your dynamically added controls that have the css class “dynamicControlCssClass,” will now have the same click event.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: