Reputation: 11
jquery;
Situation - just upgrading from pure javascript to jquery - prompted by browser inconsistencies.
On load, a page displays, in a div, the result of an ajax request, which includes an OK button, <input name="srd_button_ok" type="button" value="OK">
at the bottom.
Clicking OK button IS NOT detected by:
$('[name*="srd_button_ok"]').click (function(){
alert("srd_button_ok clicked");});
However, another 'test button' placed in a separate div on same page, permanently displayed <input name="test_div" type="button" value="Test Div">
IS detected by:
$('[name*="test_div"]').click (function(){
alert("test_dv clicked");});
Both of the above within
jQuery(document).ready(function(){ ....});
What am I missing or doing incorrectly?
Your advice will be appreciated.
Many thanks,
Ivan Rutter
Upvotes: 0
Views: 677
Reputation: 4295
The problem is that your click binding happens before the separate page is loaded into the div. You can solve this 2 ways:
Use 'live' to bind the click event.
$('[name*="test_div"]').live('click', function(){ alert("test_dv clicked");});
You can initialize the click inside the click callback.
$('#loading_div').load('some/url', function(data) {
$('#loading_div [name*="test_div"]').click(function(){ alert("test_dv clicked");});
});
Upvotes: 1
Reputation: 1762
$().click(handler) will bind an event handler to the selected elemets from the DOM hierarchy. In your case the OK button is not part of the DOM yet, since it will be loaded asynchronously (AJAX).
There are two solutions here. Either have your handler binding code executed after the AJAX loading has complete or use jQuery's .live() [docs].
Upvotes: 0
Reputation: 9031
Try this instead:
$('[name*="srd_button_ok"]').live('click', function(){
alert("srd_button_ok clicked");
});
Upvotes: 4