Your code could end up looking something like this:

function setValidation( selector, validator ) {

    $(document).ready( function() {
        var $form = $(selector);

        $form.submit( function() {

            $form.validate( validator );
            var valid = $(this).valid();
            if( valid ) {
                var form_url = $form.attr('action');
                var page_target = form_url.substr(1).replace(new RegExp("/",
"g"), "_");
                var queryString = $form.formSerialize();
                $form.ajaxSubmit({
                    type: 'post',
                    url: form_url + '/',
                    data: queryString,
                    resetForm: true,
                    success: function( response ) {
                        alert( response );
                        $( '#' + page_target ).slideToggle('slow',
function() {

$(response).hide().prependTo('#sortable').slideDown('slow');
                        });
                    }
                });
            }
            return false;

        });
    });

}

And for the case you listed, you would call it like this:

setValidation( '#newAward', validate_awards );

I threw a $(document).ready() block into that code. You don't need that if
your call to the setValidation() function is already inside a document ready
callback, but it doesn't do any harm either.

-Mike

On Tue, Nov 24, 2009 at 3:48 PM, Dave Maharaj :: WidePixels.com <
d...@widepixels.com> wrote:

> I have the exact same code on every page where a form gets submitted. How
> can i turn that into a simple function?
>
> The only thing that changes is the $(this).validate(validate_awards) and
> the
> form ID;
>
> It would be so much easier if the function was in one place and called
> where
> needed but I cant figure this out.
>
> Something like:
>
>
> $('#newAward').submit(function({
>        myFormFunction(validate_awards, '#newAward');
> });
>
>
> where I could put in the formID and the validation rules to use
>
>
> CURRENTLY HAVE THIS ON EVERY PAGE: Only the "validate_awards" and
> "#newAward" changes
>
> $('#newAward').submit(function() {
>
>
>   $(this).validate(validate_awards);
>   var valid = $(this).valid();
>   if (valid) {
>
>   var form_url =  $(this).attr('action');
>   var page_target = form_url.substr(1).replace( new RegExp( "/" ,"g"), "_"
> );
>   var queryString = $('#newAward').formSerialize();
>    $(this).ajaxSubmit({
>     type:    'post',
>     url:      form_url+'/',
>     data:      queryString,
>     resetForm:   true,
>     success:    function(response){
>            alert(response);
>             $('#'+page_target).slideToggle('slow', function (){
>              $(response).hide().prependTo('#sortable').slideDown('slow');
>
>             });
>             }
>
>
>    });
>   }
>   return false;
>
>  });
>
> Any help would be greatly appreciated.
> Thanks,
>
> Dave
>
>

Reply via email to