views:

25

answers:

1

I have a page that creates multiple forms for each object that I had selected on the previous page, and each of these forms has the id "edit_movie_[uid]". I'm trying to get jQuery to act on submit but right now all it does is make my submit buttons nonresponsive. In my application.js I have:

jQuery.ajaxSetup({
   'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
 })

 $(document).ready(function(){

   $('form[id^="edit_mov"]').submit(function(){
      $.post($(this).attr('action'), $(this).serialize(), null, 'script');
      return false;
   })
 })

As the callback for my submit button I just have:

alert("jquery works");

So an alert box should pop up, but right now none of the buttons do anything and some of them are unclickable.

A: 

Looks like you're triggering the event in your ready block rather than binding it. You can use bind, or, better yet, delegate. Also, avoid calling $() more than once:

$(function() { // Shorthand for $(document).ready()
  //$('form[id^="edit_mov"]').bind('submit', function() {
  $(document).delegate('form[id^="edit_mov"]', 'submit', function() {
    var form = $(this);
    console.log('submit triggered', form);
    $.post(form.attr('action'), form.serialize(), null, 'script');
    return false;
  })
})
fullware
Thanks for the tips. I'm new to jquery/javascript, so I've just been trying to get the code to work and the "good form" tips much appreciated.
lyrch
Glad to be of help. By the way, the delegate function is fairly new, and I think worth understanding well. The idea is that you can allow events on any element to bubble up to the document, so there is only one handler, instead of one for every single matching element. Very powerful.
fullware