I'm aware that if you load a div within a page with form elements using ajax, then you gotta use the live function to add events to those elements that were not in the dom tree....
And also I read in the jQuery website that live function does not currently support focus, blur etc....
What should I do to invoke a function when an element loaded into a div through ajax is focused or blurred...?
Is it something that should be done with bind...? but talking about bind, even though live and bind looks a little alike, it can't be used in the above mentioned scenario... right...?
and here goes the code....
<BODY style="">
<div style="margin-top:5px; width:100%" class="subAndContent" id="subAndContent">
<!-- TABLE TO HOLD SUB MENU-->
<div id="subMenuDiv">
<table width="100%" >
<tr align="center" valign="middle">
<td width="100%" valign="middle" class="rounded" >
<div class="sidebarmenu">
<ul id="sidebarmenu1">
<li>
<a href="javascript:ajaxLoadMainOnly('createHotel.php', 'content')" > <!-- This function get's the page to be loaded and the div into which it should be loaded and uses ajax to do the loading... -->
HOTEL
</a>
</li>
<li>
<a href="javascript:ajaxLoadMainOnly('createCountry.php', 'content')" >
COUNTRY
</a>
</li>
<li>
<a href="javascript:ajaxLoadMainOnly('createCity.php', 'content')">
CITY
</a>
</li>
</ul>
</div>
</td>
</tr>
</table> <!-- END TABLE TO HOLD SUB MENU-->
</div>
<div id="contentDiv" class="rounded">
<!-- TABLE TO HOLD CONTENT PANE-->
<table width="100%" style="float:left;">
<tr valign="left">
<td align="center">
<div id ="content">
<!-- Div into which the content will be loaded -->
</div>
</td>
</tr>
</table>
</div>
</div>
<!-- DIV AND TABLE TO HOLD FOOTER -->
<?php
include 'footer.php';
?>
</BODY>
You have to get hold of the elements that are loaded dynamically and then add the focus and blur handlers using bind. For example, if you want to add the handlers to a textarea with class "longtext", you might use something like:
$.getJSON('createHotel.php', { /* params go here */ }, receiveHotelCreated);
function receiveHotelCreated(data) {
$('#content textarea.longtext').bind('blur', onTABlur);
}
function onTABlur() {
var ta = $(this); // The textarea on which the blur event occurred
alert('Textarea blurred');
// Your code goes here
}
The onTABlur (TA = text area) function is to be called when the focus leaves the textarea. Inside the function, this
refers to the element the function is invoked for. As we bind it to the text area when we receive the AJAX response (receiveHotelCreated
), this is going to be the desired text area element. We wrap this
in the jQuery function ($(this)
) to get some extra functionality.