Skip to content

Instantly share code, notes, and snippets.

@mildfuzz
Created September 21, 2012 15:12
Show Gist options
  • Select an option

  • Save mildfuzz/3762080 to your computer and use it in GitHub Desktop.

Select an option

Save mildfuzz/3762080 to your computer and use it in GitHub Desktop.
My Library
/*
A collection of useful scripts
*/
//Collect all form data into a string
$.fn.getFormData = function(){
var str = "";
var areas = $(this).find('input').not('input[type=submit]').not('input[type=button]').add($(this).find('textarea')).add($(this).find('select'));
areas.each(function(i){
str += $(this).attr('name')+"="+($(this).val())+(i < areas.length-1 ? "&" : "");
});
return str;
}
//HMTL Toggle
$.fn.htmlToggle = function(a,b){
$(this).html(($(this).html() == a ? b : a));
}
//
//Depends on htmlToggle and getFormData()
//Extends form object to ajax submit the form, and replaces an element with it's twin from the ajax results.
//accepts callbacks for start, end, success and error
$.fn.submitAndFetchOnChange = function(element, start, end, success, error){
var form = $(this);
$('input[type=submit]',$(this)).remove();
$('input', $(this)).add($('select',$(this))).add($('textarea',$(this))).change(function(){
if(typeof start == 'function'){start(arguments);}
if(operation){
operation.abort();
}
var url = form.attr("action"), method = form.attr("method"), data = form.getFormData();
var operation = $.ajax({
url: url,
type: method,
data: data,
success: function(data){
$(element).animate({opacity: 0},200,function(){
$(element).html($(data).find(element)).animate({opacity: 1},200);
})
if(typeof success == 'function'){success(arguments);}
if(typeof end == 'function'){end(arguments);}
},
error: function(){
if(typeof error == 'function'){error(arguments);}
if(typeof end == 'function'){end(arguments);}
}
})
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment