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" val开发者_JAVA百科ue="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?
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.
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');
});
You can use jQuery
live event handler which work for dynamically created elements also.
Try this
$('form').live('submit', function(event) {
var $form = $(this);
var formName = $form.attr('name');
var formData = $form.serialize();
// ...
});
Following code will alert the form id of the button having 'create_btn' css, you can also access it by id if you want by changing the (.create-btn)dot to hash(#create-btn) and you can use .click or .submit instead.
<script type="text/javascript">
$(document).ready(function () {
$('.create-btn').click(function(){
alert(this.form.id);
}) ;
});
精彩评论