Last active
May 24, 2016 12:53
-
-
Save automagisch/bf8aab54ddbfdeba8597f9cfeec558d2 to your computer and use it in GitHub Desktop.
jQuery form field parser with support for radio's and checkboxes
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
/* | |
* jQuery utilities | |
* Takes in a form element and rips out all the values in a simple key-value pair | |
*/ | |
$(function() { | |
$.fn.parseFormFields = function(props) { | |
// define some default settings with default values | |
var default_props = { | |
ignored_input_types: ['submit'] // ignores several types of inputs, overridable | |
} | |
// extend some custom props on default props | |
props = $.extend(default_props, props); | |
// some used variables | |
var keyv = {}; // key value that will be retuned | |
var inp = this.find(':input'); // the target to find (:input fields) | |
// binds a value to keyv | |
function key(key, val) { | |
keyv[key] = val; | |
return val; | |
} | |
// loop over all inputs, ignoring the ones in the ignore list | |
// attach it to key value group | |
inp.each(function() { | |
if(props.ignored_input_types.indexOf($(this).attr('type')) == -1) { | |
// if this is a checkbox, I only want to know if it is checked or not | |
if($(this).attr('type') == 'checkbox') { | |
if(!keyv.hasOwnProperty($(this).attr('name'))) key($(this).attr('name'), false); | |
key($(this).attr('name'), $(this).is(':checked')); | |
return; | |
} | |
// if this is a radio, I only want to know which option is checked. Before subscribing to the list, | |
// I make sure that at least an empty field filled with 'false' is present. I only | |
// populate the value IF it is selected to have a value. | |
if($(this).attr('type') == 'radio') { | |
// only make the key if it is not yet existing | |
if(!keyv.hasOwnProperty($(this).attr('name'))) key($(this).attr('name'), false); | |
// assign value if this is the radio that is checked | |
if($(this).is(':checked')) { | |
key($(this).attr('name'), $(this).val()); | |
} | |
return; | |
} | |
// if this is a general input like text, fill it with the value. | |
key($(this).attr('name'), $(this).val()); | |
} | |
}); | |
// returns a hash with all the values | |
return keyv; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment