Question

Right now I have a Save button on a big/large form with lots of input elements (~ 500 inputs). These inputs are loaded through AJAX and a big part of them are hidden inputs.

When clicking the Save button I call:

// Save button click
$("#save").click(function ()
{
    var button = $(this);

    button.button('loading');

    if($("form").valid())
    {
        ... AJAX Post here ...
    }
    else
    {
        button.button('reset');
    }
}

The problem is that the Loading animation provided by Twitter Bootstrap button won't fire because $("form").valid() is pretty intensive and blocks the UI thread. I tested it removing the call to $("form").valid() and the Loading animation just shows as expected.

I'd like to see the Loading animation while the form is being processed. The way it is now the animation just flashes when the code passes$("form").valid()... the user can barely see it.

Is there any easy approach I can follow to give the Loading button some time while the jQuery validate valid() function is doing its work?

Was it helpful?

Solution

I managed to solve the problem in a different way...

Instead of validating the entire form with hundreds of input fields (a time consuming process), I validate only the modified fields, that is, I call $("form").validate().element(this), where this is the input element that had its valued modified by the user.

Using jQuery we can have something like this:

// Save button click
$("#save").click(function ()
{
    var button = $(this);

    button.button('loading');

    // Selecting only Questions that had their answers modified...
    var answers = // Your logic here to select the modified input fields

    var valid = true;           

    answers.each(function ()
    {
        $(this).find("textarea:not(:disabled)").each(function ()
        {
            if (!$("form").validate().element(this))
            {
                $(this).focus();

                valid = false;

                return;
            }
        });
    });

    // If any of the answers is invalid return with validation messages...
    if (!valid)
    {
        // Resetting Bootstrap's button back to it's original state
        button.button('reset');

        return;
    }

    ... // Do the AJAX POST here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top