I want the submit action on a form() to be automatically fired when all input elements within this form are completed/filled. How to do it using ajax?
views:
180answers:
2
+10
A:
Something like the following:
$("#myForm :input").blur(function() {
if($('#myForm :input[value]').length == $('#myForm :input').length) {
$(this).closest("form").submit();
}
return false;
});
Note the following:
karim79
2009-11-22 12:25:53
phew that was quick. nice one.
Richard Nguyen
2009-11-22 12:28:02
+1 for a good answer to the question, but I agree with the commenters who said it sounds like a bad idea.
RichieHindle
2009-11-22 12:32:24
I don't think the ':empty' selector will work on input fields of type text the way you expect it to work...
mtyaka
2009-11-22 12:36:47
@karim79 - It was me :) I'm testing this in Firefox 3.5. I have a form with one input element of type text. Typing $(':input:empty')[0] in the Firebug console returns that element no matter what I type into the input field.
mtyaka
2009-11-22 12:46:05
@mtyaka - You were correct. I've edited the answer, and sorry for whining about being down-voted.
karim79
2009-11-22 13:12:58
@mtyaka - check out the neat trick (at least I hope) I've used for determining if there are any empty elements.
karim79
2009-11-22 13:23:26
About the 'closest' thing: you are on the safe side. But I believe it's not allowed to have <form> within <form> (nested <form>s). I couldn't find the confirmation in HTML spec though. But the browsers don't seem to handle it correctly.
Grzegorz Oledzki
2009-11-22 13:53:28
@karim79 - This seems to work, so I changed the down- into an up-vote! Perhaps the check could even look like this: if (!$('#myForm :input:not([value])').length) { ... }
mtyaka
2009-11-22 13:57:47
A:
Update: In addition to Karim79.
$("#myForm :input").blur(function() {
var hasEmpty = false;
if($('#myForm :input[value]').length == $('#myForm :input').length) {
$(this).closest("form").submit();
var name = "", email = ""; //Get the value for name and email from the form
var dataString = 'name='+ name + '&email=' + email;
$.ajax({
type: "POST",
url: "page.aspx",
data: dataString,
success: function() {
$('#message').html("<h2>Form Submitted!</h2>");//Display message
}
});
}
return false;
});
Try this:
$("form")[0].submit();
You will need to call this function after a fields has been validate.
And check this site.
Colour Blend
2009-11-22 12:32:39