I have a form with multiple checkbox groups and at least one has to be checked if the group is required. The data comes from database so I never know if the group of checkboxes is a required field and what kind of numbers are in id-s and names.
For example a part of the html:
@for ($i = 0; $i < count($checkboxes); $i++)
<?php $j=$i+1 ?>
<?php echo ($question->required == 1 ? '<div class="checkbox required">' : '<div class="checkbox">') ?>
<label for="MultipleChoice-<?php echo $question->id; ?>">
{!! Form::checkbox('MultipleChoice-'.$question->id.'-'.$j, $checkboxes[$i], false, ['id' => 'MultipleChoice-'.$question->id]) !!}
{{$checkboxes[$i]}}
</label>
</div>
@endfor
and a part of the .js file:
jQuery.validator.messages.required="";
$('#form').validate({
ignore: '',
});
var lastPage = $('#'+ ($('.setup-content').length-1).toString())
checkboxes = lastPage.find("input[type='checkbox']"),
arrayCheckbox = new Array();
// Put all the unique name attributes in an array.
checkboxes.each(function(){
if($(this).closest(".required").length == 1){
var name = $(this).attr("id");
if($.inArray(name, arrayCheckbox) == -1)
arrayCheckbox.push(name);
}
});
for(var i=0; i<arrayCheckbox.length; i++){
var abi = checkboxes.filter("[id=" + arrayCheckbox[i] + "]")
abua = checkboxes.filter("[id=" + arrayCheckbox[i] + "]:checked").length;
console.log("#" + arrayCheckbox[i]);
$( "#" + arrayCheckbox[i] ).rules( "add", {
required: true,
minlength: 1,
messages: {
required: "Required input",
}
});
}
I have tried different things but nothing really works. The rules that I have added right now make only the first one of the checkboxes required, but it doesn't necessarily have to be checked. Just at least one from the group has to be checked.
Aucun commentaire:
Enregistrer un commentaire