Pregunta

I'm building a small app using jquery mobile and am using jqueryvalidate http://jqueryvalidation.org/ for the form validation. I managed to get a post working using ajax but as soon as I moved it into submitHandler: function(form) it still "works" but I have to click submit twice for it to work? Please help I'm baffled!

//the validation stuff
$().ready(function() {      
// validate new id form
$("#addId").validate({
    errorPlacement: function(error, element) {
        error.insertAfter(element.parent()); // <- make sure the error message appears after parent element (after textbox!)
                        },
        rules: {
            idDesc: "required",
            },
         messages: {
            idDesc: "Please enter a valid description",
                },

        submitHandler: function(form) {
            $('#submit').click(function()
            {
                              $('#addCustId').popup('close');
                              $.post("Customer_AddNewCustomerId.php", $("#addId").serialize(),  function(response)
                                        {
                                             LoadCustomerIdentificationType();
                                        });
                                    });
                            }
                    }); //end validate
                }); // end function

Thanks :)

¿Fue útil?

Solución

This is totally wrong...

submitHandler: function(form) {
    $('#submit').click(function() {  // <-- causing your double-click situation
        ....
        $.post(....);
    });
}

As per the documentation for the submitHandler callback function,

"Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated."

In other words, it only fires when button is clicked on a valid form. The plugin automatically handles the click, so wrapping the function within another click handler is pointless and counterproductive.

Just do this...

submitHandler: function(form) {
    ....
    $.post(....);
    return false;  // not necessary, but it reminds me that the default is blocked
}

You can leave out the return false; line if you wish. I always put it in (doesn't hurt anything), as it reminds me that the default action on the form is not going to happen.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top