Setting selected option in laravel form

后端 未结 14 986
春和景丽
春和景丽 2020-12-25 14:09

I need to give selected value like this html:


                        
    
提交评论

  • 2020-12-25 14:26

    Everybody talking about you go using {!! Form::select() !!} but, if all you need is to use plain simple HTML.. here is another way to do it.

    <select name="myselect">
    @foreach ($options as $key => $value)
        <option value="{{ $key }}"
        @if ($key == old('myselect', $model->option))
            selected="selected"
        @endif
        >{{ $value }}</option>
    @endforeach
    </select>
    

    the old() function is useful when you submit the form and the validation fails. So that, old() returns the previously selected value.

    0 讨论(0)
  • 2020-12-25 14:26

    You have to set the default option by passing a third argument.

    {{ Form::select('myselect', [1, 2], 2, ['id' => 'myselect']) }}
    

    You can read the documentation here.

    0 讨论(0)
  • 2020-12-25 14:26

    Another ordinary simple way this is good if there are few options in select box

    <select name="job_status">
       <option {{old('job_status',$profile->job_status)=="unemployed"? 'selected':''}}  value="unemployed">Unemployed</option>
       <option {{old('job_status',$profile->job_status)=="employed"? 'selected':''}} value="employed">Employed</option>
    </select>
    
    0 讨论(0)
  • 2020-12-25 14:32

    Just Simply paste this code you will get the desired output that you needed.

     {{ Form::select ('myselect', ['1' => 'Item 1', '2' => 'Item 2'], 2 , ['id' =>'myselect']) }}` `
    
    0 讨论(0)
  • 2020-12-25 14:37

    If you have an Eloquent Relationship between your models you can do something like that:

    @foreach ($ships as  $ship)
    <select name="data[]" class="form-control" multiple>
        @foreach ($goods_containers as  $container)
            <option value="{{ $container->id }}"
                    @if ($ship->containers->contains('container_id',$container->id ) ))
                    selected="selected"
                    @endif
            >{{ $container->number}}</option>
        @endforeach
    </select>
    @endforeach
    
    0 讨论(0)
  • 提交回复
    热议问题