select2 is not working

你说的曾经没有我的故事 提交于 2019-12-14 03:29:49

问题


My select2 is not working. It just shows up with multiple selectbox

<form action="">
<select class="js-example-basic-multiple" multiple="multiple">

<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>

<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>

<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>

  </select>
</form>
<script type="text/javascript">
                $(".js-example-basic-multiple").select2();
</script>

Error in console: Uncaught TypeError: $(...).select2 is not a function at HTMLDocument.

JS FIDDLE:

https://jsfiddle.net/y6ogss94/


回答1:


This runs fine if you have imported correctly - jQuery library, select2 js and select2 css.

Here I have imported jquery 2.0.0 and select2 css and js from their cdn and it works fine:

 $(".js-example-basic-multiple").select2();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>


<form action="">
<select class="js-example-basic-multiple" multiple="multiple">

<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>

<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>

<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>

  </select>
</form>

Note: You need to execute your select2 initialisation code only after you have included both the js libraries and DOM has loaded, which is a general practice for most jQuery plugins, not only this. So, while using this code you should write this script after including jquery and select2 scripts:

<script>
$(document).ready(function(){
  $(".js-example-basic-multiple").select2();
});//document ready
</script>


来源:https://stackoverflow.com/questions/41277344/select2-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!