what I want is that the data is NOT sent to the server unless a checkbox is selected. Previously the validation was working correctly, after a while it stopped working, not sure if it's a syntax error.
I have the following HTML:
<form class="form-group" method="post" name="form" onsubmit = "validarCI(event, this);" action="{{ action('ProductoController@store') }}" enctype="multipart/form-data">
@csrf
<table class="table" >
@foreach($costoIndirecto as $ci)
<tr>
<td>
<input type="checkbox" name="ci[]" value="{{$ci['id']}}"> {{$ci['nombre']}} - {{$ci['valor']}} Bs
</td>
</tr>
@endforeach
</table>
</form>
and the following code in JavaScript
function validarCI(e) {
var formulario = document.form;
var ci = false;
for (var i = 0; i < formulario.ci.length; i++) {
if (formulario.ci[i].checked) {
ci = true;
}
}
if (!ci){
alert ('Debe seleccionar al menos un costo indirecto');
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
To do the validation instead of using
document.form
you can usedocument.getElementsByName
to get the checkboxes:and then the validation looks like this:
You can test that the form is only sent if the checkbox is checked, if it is not checked the alert will appear.