javascript - 使用 laravel 在 bootstrap 多重选择中预先选择选定的选项

标签 javascript php jquery twitter-bootstrap laravel

我已经实现了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>

Output

最佳答案

您可以在代码中执行类似的操作:

<?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/

相关文章:

php - 调用mysql存储过程后报错

php - 在 CakePHP 的不同 Controller 中使用模型

javascript - 复杂形式 - 如何为每个新元素生成新的 object_ids?

javascript - 将 for 循环中的整数替换为字符串

javascript - 没有 package.json 的 Node.js 项目

javascript - 如果找到数组中的元素,如何将其添加到数组中?

javascript - 如何使用javascript更改背景图像的透明度?

php - 无法让登录路由在 Symfony 2 中工作

javascript - Jquery 在打字时更改输入类

java - jQuery 将 servlet 名称添加到 URL 中两次