Plot
I have some dynamic js validations that first scan for all fields in a step (HTMLElement). Basically I populate checkbox_groups with all the names and then check if at least one is checked. This works good except a certain situation.
Problem
I have some dynamic checkboxes that have names like: person[1], person[2], person[3]. Because the id is specified my error <p> appears under each checkbox instead of only the last checkboxes as intended. Basically all I want is to find a way to modify this script so in this scenario the error message to appear only after the last checkbox.
Code
/**
* Validate step checkboxes
*
* @param {HTMLElement} element
*
* @returns {Object}
*/
function validate_step_checkboxes(step) {
var checkbox_groups = [];
var errors = [];
var error = false;
$.each(step.find('input[type="checkbox"][data-required="1"]'), function () {
var myname = this.name;
if ($.inArray(myname, checkbox_groups) < 0) {
checkbox_groups.push(myname);
}
});
console.log('groups');
console.log(checkbox_groups);
// Check if there is a checkbox selected for each checkbox group
for (i = 0; i < checkbox_groups.length; i++) {
if (step.find('input[type="checkbox"][data-required="1"]:checked').length <= 0) {
$('input[type="checkbox"][data-required="1"][name="' + checkbox_groups[i] + '"]').last().closest('.checkbox-label').after('<p class="input-error">Please select one option.</p>');
errors[checkbox_groups[i]] = 'Field required';
error = true;
}
}
return !error;
}
HTML
<table class="primary-table hidden-xs">
<thead>
<tr>
<th>Name</th>
<th>X/th>
<th>x</th>
<th>x</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td>
<label class="checkbox-label">Test PErson
<input name="person[1]" type="checkbox" data-required="1">
<span class="checkmark"></span>
</label>
</td>
<td>-</td>
<td>Test</td>
<td>Test</td>
<td><a href="h#">Edit</a></td>
</tr>
<tr>
<td>
<label class="checkbox-label">Test PErson
<input name="person[2]" type="checkbox" data-required="1">
<span class="checkmark"></span>
</label>
</td>
<td>-</td>
<td>Test</td>
<td>Test</td>
<td><a href="h#">Edit</a></td>
</tr>
<tr>
<td>
<label class="checkbox-label">Test PErson
<input name="person[3]" type="checkbox" data-required="1">
<span class="checkmark"></span>
</label>
</td>
<td>-</td>
<td>Test</td>
<td>Test</td>
<td><a href="h#">Edit</a></td>
</tr>
<tr>
<td>
<label class="checkbox-label">Test PErson
<input name="person[4]" type="checkbox" data-required="1">
<span class="checkmark"></span>
</label>
</td>
<td>-</td>
<td>Test</td>
<td>Test</td>
<td><a href="h#">Edit</a></td>
</tr>
</tbody>
</table>
person[](orpeople[]).