解决方法
基本上是Kld建议的,但没有额外的按钮,因为我知道OP想要使用select的第一个选项来触发新的值模态.它会在触发select2:close事件时检查值,如果选择“NEW”,则提示输入新值,在选择框的末尾添加并选择它.
$(function () { $(".select2") .select2({ placeholder: 'Select type',width: '50%',minimumResultsForSearch: Infinity }) .on('select2:close',function() { var el = $(this); if(el.val()==="NEW") { var newval = prompt("Enter new value: "); if(newval !== null) { el.append('<option>'+newval+'</option>') .val(newval); } } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/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> <select id="mySel" class="select2"> <option></option> <option value="NEW">Add new type</option> <option>Car</option> <option>BUS</option> <option>TWO</option> <option>THREE</option> </select>