Reputation: 4021
I have a multipage document but I've been displaying html and doing validation for a single page within one php file:
<div id="checkPage" data-role="page">
<div data-role="header">
<h1>Page Title</h1>
</div>
<div data-role="content">
<?php
$form = $_REQUEST['form']; //this is simply a hidden input in my form that I reference to know if a form submission has occurred
if($form) {
$res = process();
if(is_array($res)) { //if the data is an array then it is an array of errors that I will display to the user
$html = page($res);
} else {
$html = $res; //if the data is not an array then it is confirmation html that the request was successful.
}
} else {
$html = page();
}
echo $html;
?>
</div>
</div>
In my page() function I am appending some jquery after my HTML:
$detail .= chr(10) . '<script type="text/javascript">';
$detail .= chr(10) . '$( "#checkPage" ).bind( "pageinit",function(event){';
$detail .= chr(10) . ' $("#txtAmount").change(function(){';
$detail .= chr(10) . ' alert("INSIDE");';
$detail .= chr(10) . ' });';
$detail .= chr(10) . '});';
$detail .= chr(10) . '</script>';
return $detail;
I see the alert when I navigate to my page then type-in (and leave) the amount textbox. I also see the alert if I click the cancel button on the page (where I'm redirected to another page) then return again through menu hyperlinks and type-in (and leave) the textbox again. However, if I submit the form, discover validation errors and re-display the page, the pageinit is not set again. Even if I leave off the pageinit logic the change event no longer is set.
What am I doing wrong? I appreciate any help I can get.
Upvotes: 1
Views: 1076
Reputation: 4021
Here is what finally worked. Eric J. did get me on the right track.
$detail .= chr(10) . '<script type="text/javascript">';
$detail .= chr(10) . '$("#txtAmount").die("change");';
$detail .= chr(10) . '$( "#txtAmount" ).live( "change",function(event){';
$detail .= chr(10) . ' alert("CHANGE");';
$detail .= chr(10) . '});';
$detail .= chr(10) . '</script>';
Without the die then if I navigate away and come back it will be called multiple times. But without live it will not work after form submission.
Upvotes: 0
Reputation: 150108
When you modify the DOM, you actually get a whole new set of elements. Events bound to elements that were replaced are gone, since the original DOM elements are no longer there. See the jQuery FAQ
You can use jQuery.live to bind to elements that match now and in the future.
Or, you can place your binding logic in a common function and call it after Ajax success, as outlined here
http://jetlogs.org/2009/01/29/re-binding-jquery-events-on-ajax-callbacks/
Upvotes: 2