views:

180

answers:

2

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?

+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:

  • The :input selector matches all input, textarea, select and button elements.
  • The closest selector returns the closest parent element.
karim79
phew that was quick. nice one.
Richard Nguyen
+1 for a good answer to the question, but I agree with the commenters who said it sounds like a bad idea.
RichieHindle
I don't think the ':empty' selector will work on input fields of type text the way you expect it to work...
mtyaka
@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
@mtyaka - You were correct. I've edited the answer, and sorry for whining about being down-voted.
karim79
@mtyaka - check out the neat trick (at least I hope) I've used for determining if there are any empty elements.
karim79
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
@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
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