mpen
mpen

Reputation: 283023

How to set class attribute on a per-option basis (in a select)?

I can create a <select> with something like this:

{{ Form::select('age', [
   'young' => 'Under 18',
   'adult' => '19 to 30',
   'adult2' => 'Over 30']
) }}

Which will render out like this:

<select name="age">
  <option value="young">Under 18</option>
  <option value="adult">19 to 30</option>
  <option value="adult2">Over 30</option>
</select>

But how can I add a class attribute to each of the <option>s?

If I have to write out the HTML, how can I maintain the pre-selected option based on the model data?

Upvotes: 1

Views: 38

Answers (1)

Ben Claar
Ben Claar

Reputation: 3415

As suspected, you'll need to do this yourself. I usually pass the selected option from my controller:

// Controller
return view('my-view', ['ages' => $ages, 'selectedAge' = $selectedAge]);

// my-view.blade.php
<select name="age">
@foreach ($ages as $value => $name)
    <?php $selected = ($selectedAge === $value) ? 'selected="selected"' : ''; ?>
    <option class="age-{{ $value }}" value="{{ $value }}" {{ $selected }}>
        {{ $name }}
    </option>
@endforeach
</select>

Upvotes: 1

Related Questions