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.
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
http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F
You can use jQuery.live to bind to elements that match now and in the future.
http://api.jquery.com/live/
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/