Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding jquery event when html has been added to dom via Ajax

Status
Not open for further replies.

ZendDeveloper

Programmer
Jan 3, 2009
15
GB
Hi,

Just starting with Jquery so if this is ridiculously simple then sorry!

I have a form that triggers a JQuery event to an ajax call. The Ajax does some processing and then returns a block of html to be output into the form. The Html that is injected into the dom contains radio buttons that then need to trigger another Jquery event which will do more processing for elsewhere on teh page.

Now, the first event works fine, but the event that is supposed to fire on the injected html isn't doing anything. I can only presume this is because the id's were not present on the original page load. If I put the second event inline so it is added to the page when Jquery returns the radio buttons then it fires absolutely fine.

Hope that makes sense.

This is the Jquery I am using:

Code:
jQuery.noConflict();
jQuery(document).ready(function() {

	jQuery(function() {
		dataString = jQuery("#shipping-zip-form").serialize();
		jQuery("#estimate").click(function() {
			jQuery.ajax( {
				type : "POST",
				url : "/checkout/cart/estimatePost",
				data : dataString,
				success : function(result) {

					jQuery('#shipping-estimate-form').html(result);
					jQuery('#message').html(result);
				}

			});

		});
		jQuery("#estimate-method").click(function() {
			alert('test');
			jQuery.ajax( {
				type : "POST",
				url : "/checkout/cart/estimateUpdatePost",
				data : dataString,
				success : function(result) {

					jQuery('#shopping-cart-totals-table').html(result);

				}

			});

		});

	});
});

So, the jQuery("#estimate") fires and returns the radio buttons but the jQuery("#estimate-method") won't fire after the #estimate-method id has been injected to the dom.

 
You said:
If I put the second event inline so it is added to the page when Jquery returns the radio buttons then it fires absolutely fine.

Sounds like you need to read up about "live" events:


jQuery docs said:
Binds a handler to an event (like click) for all current - and future - matched element.

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Hi Dan,

I read about live events just before I finished for the day yesterday (I would have posted otherwise). Thanks for the confirmation though. They worked perfectly!

I have to say, my first impressions of Jquery over prototype etc. is that it is so much more intuitive.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top