0

Using the following function to capture two dynamically generated form submissions, but is not preventing their submission.

$('body').delegate('.edit_faq, .new_faq', 'submit', function(e){
      e.preventDefault();
      //voodoo
    });

I was using the following, using live. This works, but live is depreciated and the end result is for this code to end up in a flexible plugin.

$('.edit_faq').add('.new_faq').live('submit', function(e){
  e.preventDefault();
  //magic
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
  • This should work. What jquery version are you using and what browser? A sample on jsfiddle would make it easier to answer, and also making a test case can uncover mistakes. – vinczemarton Sep 05 '12 at 10:08

3 Answers3

1

What you have written is actually working.

check:

http://jsfiddle.net/peuqU/

press run as jsfiddle sometimes needs a refresh before testing submits.

I have only been able to test it with chrome 23.

vinczemarton
  • 7,756
  • 6
  • 54
  • 86
0

Try on which is the recommended way, and return false:

$('body').on('submit', '.edit_faq, .new_faq', function(e){
      e.preventDefault();
     //Do your stuff here.

    });

As to why the submission still occurs, maybe you have a JS error somewhere in the page?

JAR.JAR.beans
  • 9,668
  • 4
  • 45
  • 57
0

FIXED--

The problem was that the code required being wrapped on a document onReady:

$(document).ready(function(){
  $('body').on('submit', '.edit_faq, .new_faq', function(e){
      e.preventDefault();
      //voodoo
  });
})

I occurs to me that since live did not require the ready, that maybe this is still wrong?

Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
  • this is the solution. also live requires document.ready too if I remember correctly. – vinczemarton Sep 05 '12 at 10:21
  • In the first, you are attaching the event handlers to `body` which probably doesn't exist until after the DOM content is loaded. In the second, the handlers are being attached to the `document` itself. – Dennis Sep 05 '12 at 10:29
  • SO, I can bypass the need for onready by attaching to $(document)? – Mild Fuzz Sep 05 '12 at 10:31
  • I don't think you should bypass it since there will be no guarantee that it will work consistently across browsers. – vinczemarton Sep 05 '12 at 10:32
  • 1
    @SoonDead That is how `live` works so it will work across browsers. – Dennis Sep 05 '12 at 11:04