Bootstrap框架----标签Tag输入用法--Bootstrap-tagsinput

来源:互联网 发布:java注解反射应用实例 编辑:程序博客网 时间:2024/06/08 13:53



有时候我们需要这样一种应用场景,让用户输入字符串列表,提交到后台。

这个时候我们可以选择标签Tag输入用法--Bootstrap-tagsinput。


效果图








我们在之前的文章中已经在SpringMVC基础框架的基础上应用了BootStrap的后台框架,在此基础上记录 标签Tag输入用法。

应用bootstrap模板


基础项目源码下载地址为:

SpringMVC+Shiro+MongoDB+BootStrap基础框架


我们在基础项目中已经做好了首页index的访问。
现在就在index.jsp页面和index的路由Controller上做修改,实现  标签Tag输入用法。




下载引用插件


下载地址:

http://download.csdn.net/detail/q383965374/9880926


下载解压后得到JS文件,放入项目的静态资源目录中。如图:





在页面上引用使用代码:

<script type="text/javascript"        src="/res/bootstrap-tagsinput/bootstrap-tagsinput.js"></script>




辅助实体代码

Pic.java

package com.test.domain.entity;import java.util.List;public class Pic {private String id;private String name;private String description;private List<String> tags;//标签public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public List<String> getTags() {return tags;}public void setTags(List<String> tags) {this.tags = tags;}}






JSP页面代码


index.jsp

<%@ include file="./include/header.jsp"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><style>/*bootstrap-tagsinput 样式*/.bootstrap-tagsinput {  background-color: #fff;  border: 1px solid #ccc;  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);  display: inline-block;  padding: 5px 6px;  color: #555;  vertical-align: middle;  border-radius: 4px;  width: 100%;  line-height: 22px;  cursor: text;}.bootstrap-tagsinput input {  border: none;  box-shadow: none;  outline: none;  background-color: transparent;  padding: 0;  margin: 0;  width: auto !important;  max-width: inherit;}.bootstrap-tagsinput input:focus {  border: none;  box-shadow: none;}.bootstrap-tagsinput .tag {  margin-right: 2px;  color: white;  font-size: 100%;}.bootstrap-tagsinput .tag [data-role="remove"] {  margin-left: 8px;  cursor: pointer;}.bootstrap-tagsinput .tag [data-role="remove"]:after {  content: "x";  padding: 0px 2px;}.bootstrap-tagsinput .tag [data-role="remove"]:hover {  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px    rgba(0, 0, 0, 0.05);}.bootstrap-tagsinput .tag [data-role="remove"]:hover:active {  box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);}</style>        <div id="page-wrapper">            <div id="page-inner">                <div class="row">                    <div class="col-md-12">                        <h1 class="page-header">                            标签Tag用法 <small>后台List接收</small>                        </h1>                    </div>                </div>                <!-- /. ROW  -->     <form class="form-horizontal" id="base">                 <input type="text" value="${pic.id}" id="id" name="id" hidden/>                <div class="form-group">                    <label for="name" class="col-sm-2 control-label">名称:</label>                    <div class="col-sm-10">                        <input type="text" class="form-control" id="name" name="name" value="${pic.name}"                               placeholder="">                    </div>                </div>                <div class="form-group ">                    <label class="col-sm-2 control-label">描述:</label>                    <div class="col-sm-10">                        <textarea id="description" name="description" class="form-control"                                  rows="8">${pic.description}</textarea>                    </div>                </div>                              <div class="form-group">                    <label for="tags" class="col-sm-2 control-label">标签:</label>                    <div class="col-sm-6 ">                        <input type="text" class="form-control" id="tags" name="tags"                               data-role="tagsinput" placeholder="输入标签Enter确认"/>                    </div>                </div>                <div class="form-group">                    <div class="col-sm-6 col-sm-offset-2">                        <button type="button" class="btn btn-default cancel"                                data-dismiss="modal">取消                        </button>                        <button type="button" class="btn btn-primary save"                                data-loading-text="Saving...">确认                        </button>                    </div>                </div>           </form>                  <!-- /. ROW  -->            </div>            <!-- /. PAGE INNER  -->        </div>        <!-- /. PAGE WRAPPER  -->                     <%@ include file="./include/footer.jsp"%><script type="text/javascript"        src="/res/bootstrap-tagsinput/bootstrap-tagsinput.js"></script><script type="text/javascript">/** * jQuery form 扩展获取数据 */$.fn.formGet = function(opts) {opts = $.extend({}, opts);var data = {},  els = opts.formGroup ? this.find('[form-group="' + opts.formGroup + '"]') : this.find('[name]');if (!els || !els.length) {  return data;}var fnSetValue = (function(emptyToNull) {  return emptyToNull ? function(obj, propertyChain, value, allowMulti) {    value !== '' && _fnObjectSetPropertyChainValue(obj, propertyChain, value, allowMulti)  } : _fnObjectSetPropertyChainValue})(opts.emptyToNull);els.each(function() {  var $this = $(this),    type = $this.attr('type'),    name = $this.attr('name'), // 可能为属性链    tag = this.tagName.toLowerCase();  if (tag == 'input') {    if (type == 'checkbox') {      var v = $(this).val();      if (v == 'on' || !v) {        fnSetValue(data, name, $(this).prop('checked'));      } else {        $(this).prop('checked') && fnSetValue(data, name, v, true);      }    } else if (type == 'radio') {      this.checked && fnSetValue(data, name, $this.val());    } else {      fnSetValue(data, name, $this.val());    }  } else if ('|select|textarea|'.indexOf('|' + tag + '|') > -1) {    fnSetValue(data, name, $this.val());  } else {    fnSetValue(data, name, $.trim($this.text()));  }});return data;};/**   * 内部私有方法   */  var _fnObjectGetPropertyChainValue = function(obj, propertyChain) {    /* 获取属性链的值 */    if (!obj) return;    if (!propertyChain) return obj;    var property,      chains = propertyChain.split('.'),      i = 0,      len = chains.length;    for (;      (property = chains[i]) && i < len - 1; i++) {      if (!obj[property]) return;      obj = obj[property];    }    return obj[property];  },  _fnObjectSetPropertyChainValue = function(obj, propertyChain, value, allowMulti) {    /* 设置属性链的值 */    if (!obj || !propertyChain) return;    var property,      chainObj = obj,      chains = propertyChain.split('.'),      i = 0,      len = chains.length;    for (;      (property = chains[i]) && i < len - 1; i++) {      if (!chainObj[property]) {        chainObj[property] = {};      }      chainObj = chainObj[property];    }    // 改进版:checkbox的多选可以组合为数组    if (!allowMulti || chainObj[property] === undefined) {      chainObj[property] = value;    } else {      var pv = chainObj[property];      if ($.isArray(pv)) {        pv.push(value);      } else {        chainObj[property] = [pv, value];      }    }    return obj;  };    //标签tags的赋值<c:if test="${pic.tags!=null&&pic.tags.size()>0}">var tag = "<c:forEach items="${pic.tags}" var="item">${ item},</c:forEach>";console.log(tag);$('input[data-role="tagsinput"]').tagsinput('removeAll');$('input[data-role="tagsinput"]').tagsinput('add', tag);</c:if>      $(document).ready(function () {        /*END-保存表单-END*/        $('button.save').on('click', function () {            debugger;            var data = $('#base').formGet();            data.tags = data.tags.split(',');            $.ajax({                type: "POST",                url: "/pic/save",                contentType: "application/json",                data: JSON.stringify(data),                success: function (result) {                    console.log(result);                    if (!result.code)                     {                        alert(result.data);                    } else {                        alert(result.msg);                    }                },                error: function (result) {                    alert("出错了,请稍后重试");                }            });        });    });</script></body></html>

注意给tags赋值时,和获取时都需要使用js处理一下。注意引用c标签。

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
js处理值的代码:

绑定

//标签tags的赋值<c:if test="${pic.tags!=null&&pic.tags.size()>0}">var tag = "<c:forEach items="${pic.tags}" var="item">${ item},</c:forEach>";console.log(tag);$('input[data-role="tagsinput"]').tagsinput('removeAll');$('input[data-role="tagsinput"]').tagsinput('add', tag);</c:if>


获取

var data = $('#base').formGet();            data.tags = data.tags.split(',');


还有需要引入样式

<style>/*bootstrap-tagsinput 样式*/.bootstrap-tagsinput {  background-color: #fff;  border: 1px solid #ccc;  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);  display: inline-block;  padding: 5px 6px;  color: #555;  vertical-align: middle;  border-radius: 4px;  width: 100%;  line-height: 22px;  cursor: text;}.bootstrap-tagsinput input {  border: none;  box-shadow: none;  outline: none;  background-color: transparent;  padding: 0;  margin: 0;  width: auto !important;  max-width: inherit;}.bootstrap-tagsinput input:focus {  border: none;  box-shadow: none;}.bootstrap-tagsinput .tag {  margin-right: 2px;  color: white;  font-size: 100%;}.bootstrap-tagsinput .tag [data-role="remove"] {  margin-left: 8px;  cursor: pointer;}.bootstrap-tagsinput .tag [data-role="remove"]:after {  content: "x";  padding: 0px 2px;}.bootstrap-tagsinput .tag [data-role="remove"]:hover {  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px    rgba(0, 0, 0, 0.05);}.bootstrap-tagsinput .tag [data-role="remove"]:hover:active {  box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);}</style>







后台接收代码

indexcontroller.java

package com.test.web.controller;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.test.domain.entity.Pic;import com.test.util.JSONResult;/** * IndexController *  *  */@Controllerpublic class IndexController {@RequestMapping("/")public String index(Model model) throws IOException {          model.addAttribute("hostname", "http://127.0.0.1:8080/");          Pic pic=new Pic();          List<String> tags=new ArrayList<String>();          tags.add("足球");          tags.add("棒球");          tags.add("篮球");          pic.setTags(tags);          model.addAttribute("pic", pic);return "/index";}@RequestMapping("/pic/save")@ResponseBodypublic JSONResult saveMigrateLine(@RequestBody Pic pic) {//保存pic记录//int result = save(pic);int result =1;return result > 0 ? JSONResult.success("保存成功"):JSONResult.error("保存失败!");}}