Spitfire5793 Spitfire5793 - 1 month ago 9
ASP.NET (C#) Question

Select2 JavaScript not changing select from default

Im trying to implement the Select2 JavaScript on my Asp.net website but no matter what I try it doesn't seem to be implementing and just shows the select control as it does normally. I've tried changing my scripts and looking at the examples on the select2 website but cant seem to get it.

Its probably something minor im missing im guessing, below is my code:

@model AssignerWebTool.Models.CreateUserModel
@{
ViewBag.Title = "Create User";
}
<head>
<title></title>

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
</head>

<body>
<script type="text/javascript">
$(document).ready(function () {
$("help").select2();
});
</script>

<select id="help" class="help">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
</body>

Answer

Your jQuery selector is wrong! There is no such element called help in your DOM. There is an element with Id help. So you may use the Id selector (using #)

Try this

$(document).ready(function () {
   $("#help").select2();
});

Also you need to make sure that you are loading the scripts in the proper order. Your layout will have a scripts section defined and you should invoke the page level scripts in the same scripts section only.

This should work.

<select id="help" class="help">
    <option value="AL">Alabama</option>
    <option value="WY">Wyoming</option>
</select>

@section scripts
{
  <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
  <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
  <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
  $(function () {

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

   });   

}