我已经实现了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->tInincludeds()->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>
最佳答案
您可以在代码中执行类似的操作:
<?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
作为对象来自 Controller ,则需要在 View 或 Controller 中将其更改为数组
在 Controller 中:
$listofIds = Model::pluck('id')->toArray();
或者在传递给 in_array()
函数之前在 View $listofIds->toArray()
中
关于javascript - 使用 laravel 在 bootstrap 多重选择中预先选择选定的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47012326/