Created
October 14, 2015 06:16
-
-
Save element6/f5f4627a137dd16dbf79 to your computer and use it in GitHub Desktop.
get or restore form values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//$('form').values() or $('form').values(v) | |
$.fn.values = function(data) { | |
var els = $(this).find(':input').get(); | |
if (typeof data != 'object') { | |
// return all data | |
data = {}; | |
$.each(els, function() { | |
if (this.name && !this.disabled && (this.checked | |
|| /select|textarea/i.test(this.nodeName) | |
|| /text|number|hidden|password/i.test(this.type))) { | |
if (this.type === 'checkbox' || this.type === 'radio') { | |
//multiple values goes into the same key | |
data[this.name] = data[this.name] || {}; | |
data[this.name][$(this).val()] = true; | |
} else { | |
data[this.name] = $(this).val(); | |
} | |
} | |
}); | |
return data; | |
} else { | |
$.each(els, function() { | |
if (this.name && data[this.name]) { | |
if (this.type === 'checkbox' || this.type === 'radio') { | |
$(this).prop("checked", $(this).val() in data[this.name]); | |
} else { | |
$(this).val(data[this.name]); | |
} | |
} | |
}); | |
return $(this); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment