doufu9947 2018-10-29 18:05
浏览 55
已采纳

如何验证Laravel上至少选中了一个复选框

I have this page in php and laravel. This is the code:

{!! Form::open(['route'=> 'cars.store','method'=> 'POST','name'=>'cars','files' => true] ) !!}

  <div class="DivCars" id="DivCars">
    <label>*&nbsp;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() !!}

And I have this function in javascript to validate that at least 1 checkbox must be selected.

<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>

How can I add this function to a onsubmit event? If I have this format to create forms:

{!! Form::open(['route'=> 'example.store','method'=> 'POST','files' => true] ) !!}

{!! Form::close() !!}

And how can I set a setCustomValidity() message for the checkboxes, which may appear near the checkbox list.

  • 写回答

1条回答 默认 最新

  • dsdvr06648 2018-10-29 18:18
    关注

    Give the form an ID and do

    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();
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?