Basically, the code is used to check if 'required form inputs' have been entered before submitting the form.
You setup the 'required inputs' by doing:
requiredInputs(
{
0 : ['name', 'age', ['phone', 'mobile', 'email']]
});
The 0 represents the form index on the page. The first two values, name, age, are text boxes that must be entered in order to submit the form. The nested array, phone, mobile, email are 'grouped' textboxes - At least one of these inputs must be entered. If all are empty, an error is shown.
function requiredInputs(inputArray)
{
for (var formIndex in inputArray)
{
var $form = $('form').eq(formIndex);
$form.submit(function(element)
{
for (var inputIndex in inputArray[formIndex])
{
var input = inputArray[formIndex][inputIndex];
if (typeof (input) == 'string')
{
var $input = $form.find('input[name="' + inputArray[formIndex][inputIndex] + '"]');
if ($input.val() == '')
{
$input.addClass('jsrequired');
element.preventDefault();
}
else
{
if ($input.hasClass('jsrequired'))
$input.removeClass('jsrequired');
}
}
else
{
for (var innerIndex in inputArray[formIndex][inputIndex])
{
var input = inputArray[formIndex][inputIndex][innerIndex];
if ($input.val() == '')
showError = false;
}
if (showError)
{
}
}
}
});
}
}
This function takes the array and loops over each form and the given inputs.
The typeof() check is used to check for 'single inputs' or 'grouped inputs'. If it's a single, it simply checks to see if the field is blank and if so, gives it a red border and prevents the form from submitting.
This part works fine...
The problem is with the nested, 'grouped items'. I can't think of a way to loop over these fields, check if they're empty and, if all of them are, show an error.
My idea was to loop over the grouped fields, set a boolean false if it finds an empty field and then reloop over each field to set the 'jsrequired' class and prevent the form from submitting. However, as I write this, I realise it wouldn't do what I want. It would set the error class on all grouped items if it were to find one empty field. Rather than setting the error class if it finds all empty fields...
Any ideas? :/