tags:

views:

29

answers:

1

I have a calendar where I can ad events to a list. It works like this:

  1. I click save, and data is saved to DB using jQuery.post
  2. To refresh the list, I call getList() which returns a html list of events
  3. I replace the existing list with the new one.

The problem is, that the new element is added after page load, thus not binding.

I think I'm a bit confused on how to use jQuery bind or live Here is my code:

// New event - Form Submit
jQuery('#formNewEvent').bind('submit',function() {

    var formData = jQuery('#formNewEvent').serializeArray();

    jQuery.post("/wp-content/plugins/wp-eventcal/eventcal_jquery.php", { instance: 'addNewEvent', formData : formData },
    function(data)
    {
      if(data == 1)
      {
        jQuery.post("/wp-content/plugins/wp-eventcal/eventcal_jquery.php", { instance: 'getEventList' },
        function(list) {
            jQuery('#eventList').html(list);  // List is updated here
        });
      }       
    });
  return false; //Must have this - otherwise the page just goes blank (at least for me)
}); 

I know there are similar problems out there, but I've not been able to figure out the correct solution.

+4  A: 

You just need to use live instead of bind so that newly added elements are also bound correctly.

jQuery('#formNewEvent').live('submit',function() {

    var formData = jQuery('#formNewEvent').serializeArray();

    jQuery.post("/wp-content/plugins/wp-eventcal/eventcal_jquery.php", { instance: 'addNewEvent', formData : formData },
    function(data)
    {
      if(data == 1)
      {
        jQuery.post("/wp-content/plugins/wp-eventcal/eventcal_jquery.php", { instance: 'getEventList' },
        function(list) {
            jQuery('#eventList').html(list);  // List is updated here
        });
      }       
    });

});
rosscj2533
Aaaah, so simple! I also had to add `return false` before the last closing tag. Otherwise the whole page wehnt blank.
Steven
Lovely. I came looking for a way to do something annoying, and found that there's a much better way. StackOverflow ftw! And thanks! :)
Edan Maor
@Edan - you're welcome, glad it helped you.
rosscj2533