select2选择的值不显示

时间:2017-03-08 08:48:01

标签: jquery

我正在使用select2

这是我的代码:

<select name="category" class="select2 select2-offscreen" id="category" style="width:100%" data-placeholder="Select Fields" tabindex="-1">
<option value="">Select Category</option>
<option value="1">Business</option>
<option value="7">Education</option>
<option value="5" selected="selected">Environment</option>
<option value="3">Health</option>
<option value="11">Movies</option>
<option value="4">Science</option>
<option value="2">Sports</option>
<option value="6">Tech</option>
<option value="10">Top Stories</option>      
</select>


$("#category").select2();

但它没有被选中。

任何人都知道如何让它发挥作用?

提前致谢。

3 个答案:

答案 0 :(得分:0)

最可能的问题,可能是您遇到问题的原因是您的库没有正确加载。

确保以正确的顺序加载库,如下所示:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>

$("#category").select2();
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>

<select name="category" class="select2 select2-offscreen" id="category" style="width:100%" data-placeholder="Select Fields" tabindex="-1">
<option value="">Select Category</option>
<option value="1">Business</option>
<option value="7">Education</option>
<option value="5" selected="selected">Environment</option>
<option value="3">Health</option>
<option value="11">Movies</option>
<option value="4">Science</option>
<option value="2">Sports</option>
<option value="6">Tech</option>
<option value="10">Top Stories</option>      
</select>

答案 1 :(得分:0)

对我来说工作正常,希望您使用此插件Select2 - The jQuery replacement for select boxes

$(function() {
  $('#category').select2({
    //options
  });
  
  $('#category').on('change', function(){
    console.log('Selected Value : ' + $(this).val() + ' - Selected Text : ' +  $('#category option:selected').text());
  });
  
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />



<select name="category" class="select2 select2-offscreen" id="category" style="width:100%" data-placeholder="Select Fields" tabindex="-1">
<option value="">Select Category</option>
<option value="1">Business</option>
<option value="7">Education</option>
<option value="5" selected="selected">Environment</option>
<option value="3">Health</option>
<option value="11">Movies</option>
<option value="4">Science</option>
<option value="2">Sports</option>
<option value="6">Tech</option>
<option value="10">Top Stories</option>      
</select>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

答案 2 :(得分:0)

您可以这样使用

$("#category").select2().select2("val", 'oneofthevaluehere');