【问题标题】:how to display the data entered in the form when reloading the page. In select2重新加载页面时如何显示表单中输入的数据。在选择2
【发布时间】:2021-09-06 20:33:18
【问题描述】:
<select type="text" name="user_name" class="form-control select2" style="width: 100%" >                                   
    <option></option>
    @foreach ($listUser as $items)            
    <option  value="{{$items->full_name}}">{{$items>full_name}}</option>                                 
    @endforeach   
</select>

<script type="text/javascript">
    $(function(){       
        $('.select2').select2({
        placeholder : 'Chọn người dùng',
        allowClear: true,     
      });
    })
</script>
  1. 如何在重新加载页面时显示表单中输入的数据。在select2中

【问题讨论】:

    标签: php jquery-select2


    【解决方案1】:

    首先您必须在控制器中将数据转换为正确的格式,在这里您可以看到正确的数据格式:

    var data = [
        {
            id: 1,
            full_name: 'John'
        },
        {
            id: 2,
            full_name: 'Jane'
        }
    ];
    

    您可以将正确格式的数组传递给视图,例如:

    $users = \App\Models\User::all(); // eloquent collection
    
    $users = $users->map(function ($user) {
        return ['id' => $user->id, 'full_name' => $user->full_name];
    })->toArray();
    

    它会产生这样的结果:

    array:1 [▼
      0 => array:2 [▼
        "id" => 1
        "full_name" => "John"
      ]
      0 => array:2 [▼
        "id" => 2
        "full_name" => "Jane"
      ]
    ]
    

    在您看来,您应该为 select2 准备数据,如下所示:

    <select type="text" name="user_name" class="form-control select2" style="width: 100%" >         
    </select>
    
    <script type="text/javascript">
        var users = {!! json_encode($users) !!};
    
        var data = $.map(users , function (value, key) {
            return {id: key, full_name: value};
        });
    
        $('.select2').select2({
            data: data
    
            placeholder : 'Chọn người dùng',
            allowClear: true,     
        });
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 2012-05-14
      • 2020-10-05
      相关资源
      最近更新 更多