我在php和laravel中有此页面。这是代码:
{!! Form::open(['route'=> 'cars.store','method'=> 'POST','name'=>'cars','files' => true] ) !!}
<div class="DivCars" id="DivCars">
<label>* Please select a car</label>
<div id="DivCarsCheck" class="DivCarsCheck">
<input type="checkbox" id="{{$cars->name}}" value="{{$cars->id}}" name="cars_check">
<label id="LabelCanchas" for="{{$cars->name}}">{{$cars->name}}</label>
<br>
</div>
</div>
{!! Form::close() !!}
我在javascript中具有此功能,以验证必须至少选中1个复选框。
<script type="text/javascript">
function ValidateCheck(e) {
var form = document.cars;
var at_least_1 = false;
for (var i = 0; i < formulario.cars_check.length; i++) {
if (form.cars_check[i].checked) {
at_least_1 = true;
}
}
if (!at_least_1){
alert('You must select at least 1 option from the list');
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
</script>
如何将此功能添加到 onsubmit
事件中?如果我使用这种格式来创建表单:
{!! Form::open(['route'=> 'example.store','method'=> 'POST','files' => true] ) !!}
{!! Form::close() !!}
以及如何为复选框设置 setCustomValidity()
消息,该消息可能显示在复选框列表附近。
答案 0 :(得分:0)
提供表单ID并执行
document.getElementById("formID").addEventListener("submit", function(e) {
var checks = document.querySelectorAll("[name=cars_check]");
for (var i = 0; i < checks.length; i++) {
if (checks[i].checked) return true;
}
alert('You must select at least 1 option from the list');
e.preventDefault();
});