Select2的Tags使用技巧

#Select2官网:可以在里面下载资源文件和进行样例参考

#https://select2.github.io/


#参考连接:

#https://segmentfault.com/a/1190000003795889

#http://blog.csdn.net/jiangeeq/article/details/52457351

#http://jingyan.baidu.com/article/59a015e35fb340f795886557.html

#http://stackoverflow.com/questions/12889309/get-selected-value-from-multi-value-select-boxes-by-jquery-select2


#需要引入的CSS和JS文件:

<link rel="stylesheet" href="<%=path%>/resources/bootstrap/css/bootstrap.css" >
<link rel="stylesheet" href="<%=path%>/resources/bootstrap/css/select2.min.css" >

<script src="<%=path%>/resources/bootstrap/js/select2.full.js"></script>
<script src="<%=path%>/resources/bootstrap/js/prettify.min.js"></script>
<script src="<%=path%>/resources/bootstrap/js/bootstrap.js"></script>


#实现被选中Item自动在下拉菜单中隐藏功能的CSS。

<style>

table td{word-break: keep-all;white-space:nowrap;}!important;
.select2-results__option[aria-selected=true] {
    display: false;
}
li[aria-selected=true] {
   display: none !important;
}
</style>


#html代码

<div id="USER_TAB" style="height:600px; width:1000px;">
<section id="tags" class="row">
    <div class="col-md-4">
        <p>
            <select id= "city" class="select2-results__option form-control" multiple="multiple">
              <option value = "ox" selected="selected">orange</option>
              <option value = "wx">white</option>
              <option value = "px" selected="selected">purple</option>
            </select>
        </p>
    </div>
</section>
</div>


<script>

#初始化,tags和multiple必须设置;data是新加的Option。Option中的Id就是Value。
 $("#city").select2({
    tags: true,
    multiple: true,
    data: [{id: 'sx', text: 'story'},{id: 'bx', text: 'bug'},{id: 'tx', text: 'task'}] //这里是在原来的基础上添加,而不是覆盖
});
 
 $("#city").on("select2:select",function(e){ #
console.log("select2:unselect", e.params.data.id); //新选择Option

e.params.data.disabled = true //让此元素之后不能被再选

console.log("select2:select text=", $("#city option:selected").text());  //获取所有选择Option的Text

console.log("select2:select text=", $(this).text()); //获取所有Option的Text
 
var element = e.params.data.element;
  var $element = $(element);
  element.hidden = true
   $element.detach();  //删除此元素,与remove()一样
   $(this).append($element);
   $(this).trigger("change");
});
 $("#city").on("select2:unselect",function(e){ //去除Option响应函数
var reslist=$(this).val();  //获取删除后的所有选中值系列

console.log("select2:unselect", e.params.data.id);获取被删除的Option的值
});
</script> 












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值