JQuery: Collect input data
November 17, 2010 Leave a Comment
Working on a simple data entry app I’ve ran into a need to collect data from multiple rows of input fields in order to post json data back to the server. Following is a simple jquery plugin, that in combination with few extra html attributes allows to collect data and convert it into json:
(function( $ ){
$.fn.collectFields = function(fieldSelector) {
var convert = function(type, value) {
switch (type) {
case "int" : return value ? parseInt(value) : 0;
case "float" : return value ? parseFloat(value): 0.0;
case "boolean" : return Boolean(value);
default : return value;
}
};
var result = [];
this.each(function() {
var fields = {};
$(this).find(fieldSelector).each(function(){
var name = $(this).attr('name');
if (name) {
fields[name] = convert($(this).attr("json-type"), $(this).val());
}
});
result.push(fields);
});
return result;
};
})( jQuery );
As you can see, I am using “json-type” attribute to indicate a type of the data field. In html it looks something like the following:
<tr class="player">
<td><input type="hidden" id="id__5" name="_id" value="5" class="field" /></td>
<td><input type="text" id="number__5" name="number" value="23" class="field" json-type="int"/></td>
<td><input type="text" id="name__5" name="name" value="Some Good Player" class="field"/></td>
</tr>
...
Script to collect data for all players would look something like this:
<script>
var players = $(".player").collectFields(".field");
</script>