Bootstrap框架----多条记录多文本(List)Select录入

我们在上一章节已经记录了多条记录多文本的录入
Bootstrap框架—-多条记录多文本(List)添加

我们发现 之前设计的交互都是直接手动输入的,比如性别男女。

但是我们在数据库一般保存的性别是0或者1。

这样的话,我们需要把其他一个输入框修改成下拉框选择的交互方式。

本篇文章记录多条记录多文本(List)Select录入。

效果如图:

Bootstrap框架—-多条记录多文本(List)添加的基础上进行修改。

jsp代码
html代码需要把性别的td修改成select如下:

<td>
                     <select class="form-control" name="gender">
                    <option value="0" selected="{gender}==0?'true':'false'"></option>
                    <option value="1" selected="{gender}==1?'true':'false'"></option>
                         </select>
                            </td>

性别这一栏的大小调整一下,免得看不到选择的值

      <th width="20%" class="text-center">性别</th>

js代码不需要修改

java代码

contacts实体需要把性别修改成int类型

  private int gender;// 性别

完整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" %>  
        <div id="page-wrapper">  
            <div id="page-inner">  
                <div class="row">  
                    <div class="col-md-12">  
                        <h1 class="page-header">  
              多条记录多文本select录入 <small>示例</small>  
                        </h1>  
                    </div>  
                </div>  
                <!-- /. ROW  -->  
     <div class="col-md-12 col-sm-10 col-xs-12 " style="margin-top: 30px">
     <form class="form-horizontal col-sm-6" id="channel">
                <!-- 其他联系人 -->
                <div class="form-group">
                    <label for="otherContacts" class="col-md-2 control-label">其他联系人</label>
                    <div class="col-md-10 input-group">
                    <table id="otherContants" class="table table-striped table-bordered" cellspacing="0" style="margin-bottom: 0;">
                        <thead>
                            <tr>
                              <th width="10%" class="text-center">姓名</th>
                              <th width="20%" class="text-center">电话</th>
                              <th width="*%" class="text-center">地址</th>
                              <th width="20%" class="text-center">性别</th>
                              <th width="10%"></th>
                            </tr>
                        </thead>
                        <tbody id="contactBody">
                        </tbody>
                    </table>
                        <script type="text/template" id="tpl_contact">
                        <tr>
                            <td><input type="text" class="form-control"  value="{name}" name="name"></td>
                            <td><input type="text" class="form-control"  value="{tel}" name="tel" maxlength="11"></td>
                            <td><input type="text" class="form-control"  value="{address}" name="address" ></td>
                            <td>
                     <select class="form-control" name="gender">
                    <option value="0" selected="{gender}==0?'true':'false'"></option>
                    <option value="1" selected="{gender}==1?'true':'false'"></option>
                         </select>
                            </td>
                            <td class="text-center">
                                <button type="button" class="btn btn-default btn-sm row-add" title="添加行"><i class="fa fa-plus fa-fw"></i></button>
                                <button type="button" class="btn btn-default btn-sm row-del" title="删除行"><i class="fa fa-minus fa-fw"></i></button>
                            </td>
                        </tr>
                        </script>
                    </div>
                </div>
                <div class="form-group">
                <div class="col-sm-6 text-right">
                <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>
        </div>
        <!-- /. ROW  -->   
            </div>  
            <!-- /. PAGE INNER  -->  
        </div>  
        <!-- /. PAGE WRAPPER  -->  
 <%@ include file="./include/footer.jsp"%>  
<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;
};
//基础函数结束
//业务代码开始
var $contactsBody = $('#contactBody'),
contactsTpl = $('#tpl_contact').html();
// 初始化其他联系人列表
(function (contacts) {
if (!contacts) {
    contacts = [{}];
}
var buffer = [];
for (var i = 0, contact; contact = contacts[i]; i++) {
$contactsBody.append($($.format(contactsTpl)).formSet(contact));
}
})(${cf:toJSON(channel.otherContacts)});



function _getContacts() {
var contacts = [];
$contactsBody.find('tr').each(function (index, ele) {
var row = $(ele).formGet();
if(row.name || row.tel){
if(!/^(1[0-9])\d{9}$/.test(row.tel)){
    alert("请输入正确的手机号.");
    return false;
}
contacts.push({"name":row.name,"tel":row.tel,"address":row.address,"gender":row.gender });
}
});
return contacts;
}
$contactsBody.on('click', '.row-del', function () {
    var $tr = $(this).closest('tr');
    if ($tr.parent().children().length == 1) return;
    $tr.remove();
  }).on('click', '.row-add', function () {
    var $tr = $(this).closest('tr').after($.format(contactsTpl, {}));
  });
$('button.save').on('click',function(){
       debugger;
       var data = $('#channel').formGet();


    if(_getContacts().length)
       data.otherContacts = _getContacts();
       console.log(data);
       $.ajax({
       type: "POST",
       url: "/channel/save",
       contentType: "application/json",
       data: JSON.stringify(data),
       success: function (result) {
         console.log(result);
         if (!result.code) {
           $('#channel').formSet(data);
           location.href = '/'
         }else{
                  alert(result.msg);
         }
       },
       error: function (result) {
         alert("出错了,请稍后重试");
       }
     });
    });
</script>  
</body>  
</html>

完整java代码如下:

在jsp页面代码中,初始化赋值时使用了channel.otherContacts。Channel实体如下:

/**
 * 渠道
 * 
 */
public class Channel {


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


}

Contacts实体如下:

package com.test.domain.entity;


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

    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;
    }


}

Controller代码接收实体代码如下:

package com.test.web.controller;

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

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.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();
        List<Contacts> otherContacts=new ArrayList<Contacts>();
        Contacts c=new Contacts();
        c.setAddress("测试绑定地址");
        c.setGender(1);
        c.setName("joe");
        c.setTel("13540493176");
        otherContacts.add(c);
        channel.setOtherContacts(otherContacts);
        model.addAttribute("channel", channel);
        return "/index";
    }

    @RequestMapping("/channel/save")
    @ResponseBody
    public JSONResult saveChannel(@RequestBody Channel channel) {
        int result=upsertChannel(channel);
        return  result>0?JSONResult.success(channel): JSONResult.error("手机号已存在,保存失败");
    }

    private int upsertChannel(Channel channel) {
        System.out.println(channel.getOtherContacts().size());
        return 1;
    }
}

传送结果如图:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张小凡vip

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值