Search code examples
javascriptlaravelrequiredselect-options

laravel foreach select option and required


Now I do foreach the select option and do the required but when I foreach it only required the top option, the rest refuse required. How do I requried every option?

blade:

              @foreach($student as $index => $students)

               <input type="hidden" class="form-control" name="student_id[]" value="{{$students->student_id}}">
               <input type="hidden" class="form-control" name="member_id" value="{{CurrentUser::user()->member_id}}">

               <select name="status[]" class="form-control" style="width:70%;" id="status" required>
                <option disabled selected value="" >
                 Choose...
                </option>
                <option name="status[]" value="Present">Present</option>
                <option name="status[]" value="Absent">Absent</option>
                <option name="status[]" value="Tardy">Tardy</option>
               </select><br>
                <p style="color:#D30707;font-size:5px;" id="check_status"></p>

              @endforeach

js:

              function myFunction() {

               var status = document.getElementById("status");

                if (!status.checkValidity()) {
                 document.getElementById("check_status").innerHTML = "Please choose status field.";
                } else {
                 document.getElementById("check_status").innerHTML = "";
                } 

                } 

Solution

  • When you do foreach in blade you should generate unique ids for each of your input or element you want to select later using JavaScript. Now you have situation that you have generate N number of inputs with id="status" so your JavaScript code will select only first one.

    You could instead of unique ids add some dummy class to your element and then select with JS all elements containing that class and loop trough them to check is required satisfied.