tareenmj's avatar

How to pre-select select statements in Laravel

I have a select statement with a large number of options to select. I am retrieving all of the options from my back-end and filling them in. However I would also like to select an option, which I also pass in from my backend. My code is as follows:

@for($i=0; $i<sizeof($info['userInfo']['courses']); $i++) //
                <tr class="table_row">
                    <td><select class="form-control" name="TB1_instructions_course[]" id="course" required="" value='{{$info['userInfo']['courses'][$i]}}'>
                            <option value="">Course</option>
                            @foreach($info['staticInfo']['courses'] as $course) //pull in static data
                            <option>{{$course['course']}}</option>
                            @endforeach
                        </select></td>
                    <td><input type="text" class="form-control" placeholder="C01" name="TB1_instructions_section[]" id='section' required="" value='{{$info['userInfo']['courses'][$i]}}'></td>
                    <!-- the rest of the table-->


Now the text field works perfectly and populates it accordingly, but I am unable to select the appropriate option in my select input. Any help? Can I do this without using jQuery or javascript?

0 likes
2 replies
36864's avatar

In your foreach, assuming you're passing in the id for the course you want to select as $preselected_course_id

<option @if($course->id === $preselected_course_id) selected @endif>

Or if you want it to look a bit cleaner

...
@if($course->id === $preselected_course_id)
<option selected>
@else
<option>
@endif
{{$course['course']}}
</option>
...
Snapey's avatar

or

<option {{ $course->id === $preselected_course_id ? selected: ''}}>

Please or to participate in this conversation.