Bootstrap框架----多项关联—check选择

我们之前已经记录了两种多项关联的交互方式,标签和列表
Bootstrap框架—-多项关联—标签式选择
Bootstrap框架—-多项关联—列表选择

本章记录第三种多项关联的交互–check选择,适用于中等数量的多项关联。

效果如图:
Bootstrap框架----多项关联—check选择_第1张图片

我们在之前的文章中已经在SpringMVC基础框架的基础上应用了BootStrap的后台框架,在此基础上记录 check选择。
应用bootstrap模板

基础项目源码下载地址为:
SpringMVC+Shiro+MongoDB+BootStrap基础框架

我们在基础项目中已经做好了首页index的访问。
现在就在index.jsp页面和index的路由Controller上做修改,实现 check选择,传给后台保存成List用法。

关键代码

html代码

        <div class="row">
        <div class="col-md-12">
        
        div>
  <div class="col-md-12" style="margin-top: 20px">
    
id="form_associate"> "item" items="${items}"> <div class="col-sm-1"> <div class="row"> "hidden" name="id" value="${item.relatedId}"> div> div>
div> div> -- /. ROW -->

js代码

<script type="text/javascript">

//基础函数开始
/**
 * 基础封装函数
 */
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;
};
/**
 * 格式化字符串 第一个参数为格式化模板 format('this is a {0} template!', 'format');
 * format('this is a {0.message} template!', { message: 'format'}); 等同于
 * format('this is a {message} template!', { message: 'format' });
 */
$.format = function() {
var template = arguments[0],
  templateArgs = arguments,
  stringify = function(obj) {
    if (obj == null) {
      return '';
    } else if (typeof obj === 'function') {
      return obj();
    } else if (typeof obj !== 'string') {
      return JSON.stringify ? JSON.stringify(obj) : obj;
    }
    return obj;
  };
return template.replace(/\{\w+(\.\w+)*\}/g, function(match) {
  var propChains = match.slice(1, -1).split('.');
  var index = isNaN(propChains[0]) ? 0 : +propChains.shift();
  var arg, prop;
  if (index + 1 < templateArgs.length) {
    arg = templateArgs[index + 1];
    while (prop = propChains.shift()) {
      arg = arg[prop] == null ? '' : arg[prop];
    }
    return stringify(arg);
  }
  return match;
});
};
/**
 * 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, $.trim($this.val()));
      }
    } else if ('|select|textarea|'.indexOf('|' + tag + '|') > -1) {
      fnSetValue(data, name, $this.val());
    } else {
      fnSetValue(data, name, $.trim($this.text()));
    }
  });
  return data;
};
/**
 * jQuery form 扩展绑定数据
 * 
 */
$.fn.formSet = function(data, formGroup) {
var els = formGroup ? this.find('[form-group="' + formGroup + '"]') : this.find('[name]');
if (!els || !els.length) {
  return this;
}
els.each(function() {
  var $this = $(this),
    type = $this.attr('type'),
    name = $this.attr('name'),
    tag = this.tagName.toLowerCase();
  var value = _fnObjectGetPropertyChainValue(data, name);
  if (tag == 'input') {
    if (type == 'checkbox') {
      var v = $(this).val();
      if (v == 'on' || !v) {
        this.checked = value ? 'checked' : '';
      } else {
        this.checked = $.isArray(value) && value.indexOf(v) > -1 ? 'checked' : ''
      }
    } else if (type == 'radio') {
      this.checked = $this.val() == String(value) ? 'checked' : '';
    } else {
      $this.val(value);
    }
  } else if ('|select|textarea|'.indexOf('|' + tag + '|') > -1) {
    $this.val(value);
  } else {
    $this.html(value);
  }
});
return this;
};
//基础函数结束


  $(function(){
        $('#btnSave').click(function(){
            $(this).button('loading');
            var arr = [];
            $('#form_associate div.row').each(function(){
                arr.push($(this).formGet());
            });
            console.log(arr);
            $.ajax({
                type: "POST",
                url: "/channel/save?id=" + ${channel.id},
                contentType: "application/json",
                data: JSON.stringify(arr),
                success: function (result) {
                  console.log(result);
                  if (!result.code) {
                    location.href = '/'
                  }else{
                    alert(result.msg);
                  }
                },
                error: function (result) {
                  alert("出错了,请稍后重试");
                }
              });
        });  
    });
script>

完整的jsp代码如下:

<%@ include file="./include/header.jsp"%>  
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<%@ taglib prefix="cf" uri="com.data.web.view.function" %>  
"page-wrapper">
"page-inner">
class="row">
class="col-md-12">

class="page-header"> 多项关联 check选择

class="row">
class="col-md-12">
class="col-md-12" style="margin-top: 20px">
"form_associate"> var="item" items="${items}">
class="col-sm-1">
class="row"> type="hidden" name="id" value="${item.relatedId}">
<%@ include file="./include/footer.jsp"%>

完整的java代码

Channel实体

package com.test.domain.entity;

import java.util.Date;
import java.util.List;

public class Channel {
    private String id;
    private String name;// 名字
    private int category;// 类别
    private String affiliation;// 归属
    private String address;// 地址
    private List otherContacts;// 其他联系人
    private String remarks;// 备注
    private int status;// 状态
    private Date createTime;// 新增时间

    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 int getCategory() {
        return category;
    }

    public void setCategory(int category) {
        this.category = category;
    }

    public String getAffiliation() {
        return affiliation;
    }

    public void setAffiliation(String affiliation) {
        this.affiliation = affiliation;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public List getOtherContacts() {
        return otherContacts;
    }

    public void setOtherContacts(List otherContacts) {
        this.otherContacts = otherContacts;
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

}

Contacts实体

package com.test.domain.entity;


public class Contacts {
    private String relatedId;
    private String name;// 姓名
    private String tel;// 电话
    private String address;// 地址
    private int gender;// 性别




    public String getRelatedId() {
        return relatedId;
    }
    public void setRelatedId(String relatedId) {
        this.relatedId = relatedId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public int getGender() {
        return gender;
    }
    public void setGender(int gender) {
        this.gender = gender;
    }


}

IndexController代码

package com.test.web.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.test.domain.entity.Channel;
import com.test.domain.entity.Contacts;
import com.test.web.message.response.JSONResult;

/**
 * IndexController
 * 
 * 
 */
@Controller
public class IndexController {

    @Autowired
    MongoTemplate mongoTemplate;

    DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");



    @RequestMapping("/")
    public String index(Model model) throws IOException {
        Channel channel=new Channel();
        channel.setId("999");
        List contacts=new ArrayList();
        Contacts c=new Contacts();
        c.setRelatedId("01");
        c.setAddress("测试绑定地址");
        c.setGender(1);
        c.setName("joe");
        c.setTel("13540493176");
        contacts.add(c);
        channel.setOtherContacts(contacts);

        List items=new ArrayList();
        Contacts c1=new Contacts();
        c1.setRelatedId("01");
        c1.setAddress("测试绑定地址");
        c1.setGender(1);
        c1.setName("joe");
        c1.setTel("13540493176");
        items.add(c1);
        Contacts c2=new Contacts();
        c2.setRelatedId("02");
        c2.setAddress("测试绑定地址");
        c2.setGender(1);
        c2.setName("zoe");
        c2.setTel("13540493199");
        items.add(c2);
        Contacts c3=new Contacts();
        c3.setRelatedId("03");
        c3.setAddress("测试绑定地址");
        c3.setGender(1);
        c3.setName("loe");
        c3.setTel("13540493159");
        items.add(c3);


        Map idCheck = new HashMap();
        if (channel != null && channel.getOtherContacts() != null) {
            for (Contacts item : channel.getOtherContacts()) {
                idCheck.put(item.getRelatedId(), Boolean.TRUE);
            }
        }
        model.addAttribute("idCheck", idCheck);
        model.addAttribute("items", items);
        model.addAttribute("channel", channel);
        return "/index";
    }


    @RequestMapping("/channel/save")
    @ResponseBody
    public JSONResult saveChannel(@RequestBody List list,@RequestParam String id) {
        List docIds = new ArrayList();
        for (Object object : list) {
            Map item = (Map) object;
            if ((Boolean) item.get("idcheck")) {
                docIds.add((String) item.get("id"));
            }
        }
        int result=upsertChannel(docIds,id);
        return  result>0?JSONResult.success(id): JSONResult.error("手机号已存在,保存失败");
    }

    private int upsertChannel(List docIds, String id) {
        System.out.println(id);
        return 1;
    }

}

传输效果如图:
Bootstrap框架----多项关联—check选择_第2张图片

你可能感兴趣的:(web,web模块积累)