我已经在我的应用程序中实现了bootstrap multi-select以进行多选。我在编辑表单中预先选择值时遇到问题。以下是我使用的js代码:

<script>
    $(document).ready(function() {
            $('#tincludeds').multiselect({
            includeSelectAllOption: true,
            selectAllJustVisible: false,
            enableFiltering: true,
            numberDisplayed: 1,
            maxHeight: 600,
            buttonWidth: '400px',
            select: {!! json_encode($tour->tIncludeds()->allRelatedIds()) !!}
        });
    });
</script>


但是脚本不起作用。我在这里有什么想念的吗?以下是{{ dd(json_encode($tour->tIncludeds()->allRelatedIds())) }}的输出

我认为多选字段的HTML代码:

<div class="form-group">
    <label for="tincluded">Includeds</label>
    <select class="form-control" id="tincludeds" multiple="multiple" name="tincludeds[]" class="tincluded">
        @foreach($tincludeds as $included)
        <option value="{{ $included->id }}">{{ $included->name }}</option>t
        @endforeach
    </select>
    @if ($errors->has('tincludeds'))
    <span class="help-block">{{$errors->first('tincludeds')}}</span>
    @endif
</div>


javascript - 使用laravel预先选择多重引导选择中的选定选项-LMLPHP

最佳答案

您可以在代码中执行以下操作:

<?php
    $listofIds = $tour->tIncludeds()->allRelatedIds(); // array with list of ids
?>
<div class="form-group">
    <label for="tincluded">Includeds</label>
    <select class="form-control" id="tincludeds" multiple="multiple" name="tincludeds[]" class="tincluded">
        @foreach($tincludeds as $included)
           <option value="{{ $included->id }}" <?php echo in_array($included->id, $listofIds) ? 'selected' : ''?> >{{ $included->name }}</option>
        @endforeach
    </select>
    @if ($errors->has('tincludeds'))
    <span class="help-block">{{$errors->first('tincludeds')}}</span>
    @endif
</div>


如果$listofIds来自控制器作为对象,则需要在视图或控制器中将其更改为数组
在控制器中:

$listofIds = Model::pluck('id')->toArray();


或者在传递给$listofIds->toArray()函数之前在View in_array()

关于javascript - 使用laravel预先选择多重引导选择中的选定选项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47012326/

10-12 12:38
查看更多