Define the selected option with the old input in Laravel / Blade

后端 未结 14 906
孤街浪徒
孤街浪徒 2020-12-04 22:04

I have this code:


                        
    
提交评论

  • 2020-12-04 22:21
    <select name="gender" class="form-control" id="gender">
                                    <option value="">Select Gender</option>
                                    <option value="M" @if (old('gender') == "M") {{ 'selected' }} @endif>Male</option>
                                    <option value="F" @if (old('gender') == "F") {{ 'selected' }} @endif>Female</option>
                                </select>
    
    0 讨论(0)
  • 2020-12-04 22:22

    Okay, my 2 cents, using the default value of Laravel's old() function.

    <select name="type">
        @foreach($options as $key => $text)
            <option @if((int) old('type', $selectedOption) === $key) selected @endif value="{{ $key }}">{{ $text }}</option>
        @endforeach
    </select>
    
    0 讨论(0)
  • 2020-12-04 22:24

    Also, you can use the ? operator to avoid having to use @if @else @endif syntax. Change:

    @if (Input::old('title') == $key)
          <option value="{{ $key }}" selected>{{ $val }}</option>
    @else
          <option value="{{ $key }}">{{ $val }}</option>
    @endif
    

    Simply to:

    <option value="{{ $key }}" {{ (Input::old("title") == $key ? "selected":"") }}>{{ $val }}</option>
    
    0 讨论(0)
  • 2020-12-04 22:31
    <select>
        @if(old('value') =={{$key}})
         <option value="value" selected>{{$value}}</option>
        @else
         <option value="value">{{$value}}</option>
        @endif
    </select>
    
    0 讨论(0)
  • 2020-12-04 22:33

    Instead of using Input class you can also use old() helper to make this even shorter.

    <option {{ old('name') == $key ? "selected" : "" }} value="{{ $value }}">
    
    0 讨论(0)
  • 提交回复
    热议问题