views:

69

answers:

2

Hello guys I am trying to add a click event on the element that is return from the server via ajax. Apparently, I have to attached my js file inside my return response instead of my main script. Is this the best practice? Do I have to create the separated js file to add event on the return text??

Example:

My Jquery - selectWeek.js

$(document).ready(function(){

//handle ajax..
 var url="sendSchedule.php";
$.post(
 url,
 {week:input},
 function(responseText){

   $("#ajax").html(responseText);

   },
   "html"

  );

// click on #add button

    $("#add").click(function(){
 //do something
 return false;
    });
});

My main page

<script type="text/javascript" src="JS/selectWeek.js"></script>


</HEAD>
<BODY>
//the code that trigger ajax is omitted

<div id=ajax>
   //the response text will be inserted here
</div>


 </BODY>
</HTML>

response from the server

// display html (omit)


// Do I have to attach the same js file to let #add listen the event?
<script type="text/javascript" src="JS/selectWeek.js"></script> 

<form>
  <input type='button' id='add' value='add'/>   
</form>

I am not sure if i make my question clear. I want to know if I need to add events on the return text. Do I have to add js file link on the return text or there is a way to do it on the main page. I just want to write my js code on the main page and keep it simple. Thanks for any reply.

+1  A: 

Try jquery live events. These events allow you to attach events to the dom as new elements are added. For instance I run my page and this page calls an ajax get/post that inserts a div with id "mydiv" to the dom. My live event will hook to the newly added div. This way you can keep all the necessary javascript for a single page in one library. Check it out it is very useful.

John Hartsock
Thanks. Very useful information.
Jerry
+1  A: 

You must call your js file in page include input <input type='button' id='add' value='add'/>

If not the code $("#add").click(function(){ will not find element called #add

canhnm
I see. Thanks for the reply. I believe John's answer is good too.
Jerry