如何创建多选框以创建标签

时间:2017-10-27 00:56:06

标签: javascript html css twitter-bootstrap

我想要一个多选框来创建标签,我使用此代码并从https://github.com/select2/select2下载select2.min.cssselect2.min.js并复制到项目中的css和js文件中, 我在html文件中的代码在这里:

<link rel="stylesheet"href="https: 
//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link type="text/css" rel="stylesheet" href="
        {{asset('css/select2.min.css')}}">
   <script type="text/javascript" src="{{asset('js/select2.full.min.js')}}">
      </script>
  <script type="text/javascript" 
  src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
  </script>
  <script type="text/javascript" src="{{asset('js/select2.min.js')}}">
   </script>

<div class="form-group">
        <label class="control-label col-sm-2" for="tags">tags:</label>
        <select class="form-control select2-multi" name="tags" 
        multiple="multiple">
            @foreach($tags as $tag)
                <option value='{{$tag->id}}'>{{$tag->name}}</option>
            @endforeach
        </select>
    </div>
  <script>

  $('.select2-multi').select2();


</script>

但是这段代码对我不起作用,我怎么能修复它? 此代码的图片位于:enter image description here

1 个答案:

答案 0 :(得分:0)

您需要在项目中包含jQuery,因为$将是未定义的。以下是样本:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>

<div class="form-group">
    <label class="control-label col-sm-2" for="tags">tags:</label>
    <select class="form-control select2-multi" name="tags" multiple="multiple">
        <option value='tag1'>tag 1</option>
        <option value='tag2'>tag 2</option>
        <option value='tag3'>tag 3</option>
    </select>
</div>

<script>
    $('.select2-multi').select2();
</script>

但是,将您的JS代码包含在DOM中就像是一个很好的做法:

$(function(){
  $('.select2-multi').select2();
});