Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve submitted form's ID and/or Name with jQuery .submit()

I've loaded few forms using .load() to different DIVs. The loaded file looks like the following example.

<div id="block_id-299">
  <div id="content">
    <form name="form1" method="post">
      <input type="submit" name="field1" value="Submit">
    </form>
  </div>
</div>

And now I am trying to retrieve submitted form's name and later, it's values using .serialize(). I was using $('form').submit(function(){ ... } but since I am loading the form dynamically, this does not work anymore.

Any help?

PS: The event can be catched using $(document).submit(function(){ but how to get form's name and/or ID?

like image 546
Prasad N Avatar asked Dec 04 '22 20:12

Prasad N


2 Answers

You can do this with $().delegate:

$(document).delegate('form', 'submit', function(event) {
    var $form = $(this);
    var id = $form.attr('id');
    var data = $form.serialize();
    // ...
});

This works even on forms added after you called delegate().

This works by listening for submit events the bubbled up to document, and by testing if the even originates from a form element.

This is similar to $('form').live('click', ...), but doesn't initially executes the selector.

See .delegate() and .live() documentation.

like image 109
Arnaud Le Blanc Avatar answered Dec 08 '22 05:12

Arnaud Le Blanc


To get the form attributes while submitting form, we can also get using the submit function. For example:

$("form").submit(function(){
  var form = $(this);
  var id = form.attr('id');
  alert(id + ' form submitted');
});
like image 26
Srinivasan.S Avatar answered Dec 08 '22 04:12

Srinivasan.S