(function ($) {
$(function () {
var addFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $formGroupClone = $formGroup.clone();
$(this)
.toggleClass('btn-success btn-add btn-danger btn-remove')
.html('–');
$formGroupClone.find('input').val('');
$formGroupClone.find('.concept').text('Phone');
$formGroupClone.insertAfter($formGroup);
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') <= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', true);
}
};
var removeFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') >= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', false);
}
$formGroup.remove();
};
var selectFormGroup = function (event) {
event.preventDefault();
var $selectGroup = $(this).closest('.input-group-select');
var param = $(this).attr("href").replace("#","");
var concept = $(this).text();
$selectGroup.find('.concept').text(concept);
$selectGroup.find('.input-group-select-val').val(param);
}
var countFormGroup = function ($form) {
return $form.find('.form-group').length;
};
/* collectData Function~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~/
This function given a group of elements (in classic selector format) will assign each element
the values of the closest fields as a unique name and the user entered value (if any.)
Use the console to see it gather data.
*/
var collectData = function(ele) {
var $tgt = $(ele);
$tgt.each(function(index) {
// $tgt == $(this)
var $fieldNames = $(this).next('.input-group-select-val').val();
var $fieldValues = $(this).closest('.form-group').find('.form-control').val();
// Including index to each $fieldName in order to make each key/value pair unique.
$(this).attr('name', $fieldNames+index);
console.log('name: '+$(this).attr('name'));
$(this).val($fieldValues);
console.log('value: '+$(this).val());
});
}
$(document).on('click', '.btn-add', addFormGroup);
$(document).on('click', '.btn-remove', removeFormGroup);
$(document).on('click', '.dropdown-menu a', selectFormGroup);
// Clicking the #data button will call the collectData('.cache') function.
$('#data').click(function(e){
collectData('.cache');
e.preventDefault();
});
});
})(jQuery);