【JavaScript】checkBox的多选行信息获取时间:2021-12-23 11:47:06页面的列表table显示(后台model.addAttribute("page", page);传来page信息,page通过foreach标签迭代展示表格数据): <!-- CRUD按钮区域 --> <div class="page-content"> <!-- /.page-header --> <div class="row"> <div class="col-xs-6" style="margin-top: 3px;"> <button style="display: none;" class="btn_new btn-primary btn-default btn-bold md-trigger" data-modal="modal-2">新增</button> <button style="display: none;" class="btn_new btn-primary btn-default btn-bold md-trigger" onclick="edit()" data-modal="modal-3">编辑</button> <button style="display: none;" class="btn_new btn-primary btn-default btn-bold" onclick="batchDelete()">删除</button> <button class="btn_new btn-primary btn-default btn-bold md-trigger" data-modal="modal-1">查询</button> <button class="btn_new btn-primary btn-default btn-bold" onclick="uniCar()">提总组车</button> </div> <div class="col-xs-6" style="margin-top: 5px;float:right;"> <div class="dataTables_paginate paging_simple_numbers" id="sample-table-2_paginate"> <ul class="pagination"> <%@include file="commonPager.jsp"%> </ul> </div> </div> </div> </div> <!-- -----------------------------------------------------------------------------列表显示区域------------------------------------------------------------------------------------------ --> <!-- 列表显示区域 --> <div class="hr hr-18 dotted"></div> <div class="row"> <div class="col-xs-12"> <div class="row"> <div class="col-xs-12"> <div id="chenkbox"> <table id="sample-table-2" class="table table-bordered"> <thead class="fixedHeader"> <tr> <td class="tc min-10">选择</td> <td class="tc min-18" sort="int"><span>序号</span><div class="ww"></div></td> <td class="tc min-24" sort="string"><span>商品编码</span><div class="ww"></div></td> <td class="tc min-24" sort="string"><span>商品条码</span><div class="ww"></div></td> <td class="tc min-24" sort="string"><span>商品名称</span><div class="ww"></div></td> <td class="tc min-24" sort="int"><span>商品总数</span><div class="ww"></div></td> <td class="tc min-12" sort="string" style="display:none"><span>仓库</span><div class="ww"></div></td> </tr> </thead> <tbody class="scrollContent" id="tbodyId"> <c:forEach items="${page.results}" varStatus="status" var="single"> <tr> <td class="min-10 td_center"> <label class="position-relative"> <input type="checkbox" class="ace" value="${single.id}" id="checkbox" name="checkbox" /> <span class="lbl"></span> </label> </td> <td class="min-18 td_center" id="one">${status.index+1}</td> <td class="min-24 td_center" id="two">${single.itemnumber}</td> <td class="min-24 td_center" id="three">${single.displayitemnumber}</td> <td class="min-24 td_center" id="four">${single.description}</td> <td class="min-24 td_center" id="five">${single.cnt}</td> <td class="min-12 td_center" style="display:none" id="six">${single.whid}</td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> </div> </div> 效果如下: 当勾选选择框(多选)以后,点击提总组车,需要把勾选行的所有商品编码,商品条码等信息全部传到后台页面,js代码如下: function uniCar(){ var tr= getCheckBoxs('checkbox'); if (tr.length == 0) { SimplePop.alert('未选择要提总组车的信息!'); return false; } var checkcodes = ''; var object = ''; var $tr; $("#tbodyId input[type='checkbox']").each(function(i,e){ checked = $(this).prop("checked"); if(checked){ $tr = $(this).parent().parent().parent(); object += $tr.find("#two").text()+","+$tr.find("#three").text()+","+$tr.find("#four").text()+","+$tr.find("#six").text()+":"; } }); $.ajax({ url:"uniCar", data:{ 'object':object, }, dataType:"json", success:function(r){ if(r.code == '000000'){ /* if(confirm("执行成功!")){ document.location.href = "getOrderTasksPage?"+_csrfName+"="+_csrfValue; } */ SimplePop.confirm("执行成功!", { confirm:function(){ document.location.href = "getOrderTasksPage?"+_csrfName+"="+_csrfValue;} }) }else{ SimplePop.alert("执行失败"); } }, error:function(r){ SimplePop.alert("执行失败", r.msg); } }) } 后台controller接收的代码如下: /** *提总组车执行 * @param bean * @return * @throws Exception */ @RequestMapping(value = "/uniCar" , method = {RequestMethod.GET , RequestMethod.POST }) @ResponseBody public Map<String,Object> uniCar(@RequestParam("object") String object) throws Exception{ Map<String,Object> map = new HashMap<String,Object>(); try { int res = orderTasksConsumer.uniCar(object); if(res > 0){ map.put(ItemContants.CODE, ItemContants.SUCCESS_CODE); map.put(ItemContants.MESSAGE, ItemContants.SUCCESS_MESSAGE); }else{ map.put(ItemContants.CODE, ItemContants.ERROR_UPDATE_CODE); map.put(ItemContants.MESSAGE, ItemContants.ERROR_UPDATE_MSG); } } catch (Exception e) { e.printStackTrace(); map.put(ItemContants.CODE, ItemContants.ERROR_UPDATE_CODE); map.put(ItemContants.MESSAGE, ItemContants.ERROR_UPDATE_MESSAGE); } return map; } 后台consumer代码如下:(将传过来的string字符串以连接符:分解,得到的String[] object里面存的是每行tr的信息,每个tr包含该行的所有属性信息,由逗号“,”连接,在下一层service分解) @Transactional(readOnly = false,rollbackFor = Exception.class) public int uniCar(String objects) throws ScnException { String[] object = objects.split(":"); try { for(int i = 0; i < object.length; i++){ String kid = object[i]; orderTasksService.uniCar(kid); } return 1; } catch (Exception e) { ScnException exp = new ScnException(e); exp.setErrorCode(ItemContants.ERROR_UPDATE_CODE); exp.setErrorMsg(ItemContants.ERROR_UPDATE_MESSAGE); throw exp; } } 后台service代码如下: public void uniCar(String bean) throws ScnException { String[] kid = bean.split(","); Map<String,Object> reqMap = new HashMap<String, Object>(); reqMap.put("itemnumber",kid[0]); reqMap.put("displayitemnumber",kid[1]); reqMap.put("description",kid[2]); reqMap.put("whid",kid[3]); try { orderTasksDao.updateSpOrderTasks(reqMap); orderTasksDao.updateSpOrderMain(reqMap); orderTasksDao.updateSpPickedDetail(reqMap); } catch (Exception e) { ScnException exp = new ScnException(e); exp.setErrorCode(ItemContants.ERROR_UPDATE_CODE); exp.setErrorMsg(ItemContants.ERROR_UPDATE_MESSAGE); throw exp; } } 如果是只选择每行的id信息传到后台可以这么写 (以选择每行的id传到后台用来删除为例,注意在jsp页面,checkbox的value里面保存了id信息,在jsp初始化显示表格数据的时候就要如下设置) <input type="checkbox" class="ace" value="${single.id}" id="checkbox" name="checkbox" /> <span class="lbl"></span> -------------------下面是通过获取id删除的js function batchDelete() { SimplePop.confirm("确认删除?", { type: "error", confirm:function(){ var serialNumcodes = ''; var count = 0; $("#serialNum input[type='checkbox']").each(function(i,e){ var checked = $(this).prop("checked"); if(checked){ serialNumcodes += $(this).val()+","; count++; } }); if(serialNumcodes == ''){ SimplePop.alert('未选择要批处理的信息!'); return false; } $.ajax({ url : "deleteSerialNum", data : {'serialNumcodes':serialNumcodes}, type : "get", error : function(msg) { // 若Ajax处理失败后返回的信息 SimplePop.alert('删除失败。。。'); }, success : function(data) {// ajax返回的数据 var searchParams = getSearchParams("search"); var url = "getSerialNumPage?"+_csrfName+"="+_csrfValue; goBackList(url,searchParams,"POST"); } }); } }); } 上面js代码中的 getSearchParams("search");和 goBackList(url,searchParams,"POST");来自style.js(全文如下:) function table(table) { var Sys = (function(ua) { var s = {}; s.IE = ua.match(/msie ([\d.]+)/) ? true : false; s.Firefox = ua.match(/firefox\/([\d.]+)/) ? true : false; s.Chrome = ua.match(/chrome\/([\d.]+)/) ? true : false; s.IE6 = (s.IE && ([ /MSIE (\d)\.0/i.exec(navigator.userAgent) ][0][1] == 6)) ? true : false; s.IE7 = (s.IE && ([ /MSIE (\d)\.0/i.exec(navigator.userAgent) ][0][1] == 7)) ? true : false; s.IE8 = (s.IE && ([ /MSIE (\d)\.0/i.exec(navigator.userAgent) ][0][1] == 8)) ? true : false; return s; })(navigator.userAgent.toLowerCase()); function $(Id) { return document.getElementById(Id); } ; function addListener(element, e, fn) { element.addEventListener ? element.addEventListener(e, fn, false) : element.attachEvent("on" + e, fn); } ; function removeListener(element, e, fn) { element.removeEventListener ? element.removeEventListener(e, fn, false) : element.detachEvent("on" + e, fn); } ; var Css = function(e, o) { if (typeof o == "string") { e.style.cssText = o; return; } for ( var i in o) e.style[i] = o[i]; }; var Bind = function(object, fun) { var args = Array.prototype.slice.call(arguments).slice(2); return function() { return fun.apply(object, args); }; }; var BindAsEventListener = function(object, fun) { var args = Array.prototype.slice.call(arguments).slice(2); return function(event) { return fun.apply(object, [ event || window.event ].concat(args)); }; }; var Extend = function(destination, source) { for ( var property in source) { destination[property] = source[property]; } ; }; var Class = function(properties) { var _class = function() { return (arguments[0] !== null && this.initialize && typeof (this.initialize) == 'function') ? this.initialize .apply(this, arguments) : this; }; _class.prototype = properties; return _class; }; var Table = new Class( { initialize : function(tab, set) { this.table = tab; this.thead = tab.getElementsByTagName('thead')[0]; // 常用的dom元素做成索引 this.theadtds = this.thead.getElementsByTagName('td'); // this.rows = []; // 里面tbodys记录所有tr的引用 // 这里用数组记录是因为数组有reverse方法,可以用来正序,反序 this.clos = {}; // 里面记录所有列元素的引用 this.edits = {}; // 编辑表格的规则和提示 this.sortCol = null; // 记录哪列正在排序中 this.inputtd = null; // 记录哪个input被编辑了 this.closarg = { tdnum : null, totdnum : null, closmove : BindAsEventListener(this, this.closmove), closup : BindAsEventListener(this, this.closup) }; // 关于列拖拽的一些属性方法 this.widtharg = { td : null, nexttd : null, x : 0, tdwidth : 0, nexttdwidth : 0, widthmove : BindAsEventListener(this, this.widthmove), widthup : BindAsEventListener(this, this.widthup) }; var i = 0, j = 0, d = document, rows = tab.tBodies[0].rows, tds1 = tab.tBodies[0] .getElementsByTagName('td'), edit = []; var divs = this.thead.getElementsByTagName('div'); this.input = d.createElement('input'); // 编辑用的input this.input.type = "text"; this.input.className = 'edit'; this.img = d.body.appendChild(d.createElement('div')); this.img.className = "cc"; this.line = d.body.appendChild(d.createElement('div')); this.line.className = 'line'; this.line.style.top = tab.offsetTop + "px"; if (Sys.IE6) { this.checkbox = {}; // 记录那些checkbox被选中了 处理ie6不兼容的问题 var checkboxs = tab.getElementsByTagName('input'), k = 0; for (var lll = checkboxs.length; k < lll; k++) checkboxs[k].type == "checkbox" && addListener( checkboxs[k], "click", Bind( this, function(elm, k) { elm.checked == true ? (this.checkbox[k] = elm) : (delete this.checkbox[k]); }, checkboxs[k], k)); } ; for (var l = set.length; i < l; i++) { addListener(this.theadtds[set[i].id], 'click', Bind( this, this.sortTable, this.theadtds[set[i].id], set[i].id, set[i].type)); set[i].edit && (this.edits[set[i].id] = { rule : set[i].edit.rule, message : set[i].edit.message }); } ; for (l = rows.length; j < l; j++) this.rows[j] = rows[j]; for (var k = 0, l = this.theadtds.length; k < l; k++) { this.clos[k] = []; this.theadtds[k].setAttribute('clos', k), addListener( this.theadtds[k], 'mousedown', BindAsEventListener(this, this.closdrag)); } for (var i = 0, l = tds1.length; i < l; i++) { var p = i < this.theadtds.length - 1 ? i : i % this.theadtds.length; this.clos[p][this.clos[p].length] = tds1[i]; this.edits[p] && tds1[i].setAttribute('edit', p); } for (var i = 0, l = divs.length; i < l; i++) { addListener(divs[i], 'mousedown', BindAsEventListener( this, this.widthdrag)); } /*---------------------------------------------*/ /*---------------------------------------------*/ addListener(this.thead, 'mouseover', BindAsEventListener( this, this.theadhover)); addListener(tab.tBodies[0], 'dblclick', BindAsEventListener(this, this.edit)); addListener(this.input, 'blur', Bind(this, this.save, this.input)); }, theadhover : function(e) { e = e || window.event; var obj = e.srcElement || e.target; if (obj.nodeName.toLowerCase() == 'td') this.closarg.totdnum = (obj).getAttribute('clos'); else if (obj.nodeName.toLowerCase() == 'div') obj.style.cursor = "sw-resize"; }, widthdrag : function(e) { if (Sys.IE) { e.cancelBubble = true } else { e.stopPropagation() } this.widtharg.x = e.clientX; this.widtharg.td = (e.srcElement || e.target).parentNode; if (Sys.IE) { this.widtharg.nexttd = this.widtharg.td.nextSibling; } else { this.widtharg.nexttd = this.widtharg.td.nextSibling.nextSibling; } this.widtharg.tdwidth = this.widtharg.td.offsetWidth; this.widtharg.nexttdwidth = this.widtharg.nexttd.offsetWidth; this.line.style.height = this.table.offsetHeight + "px"; addListener(document, 'mousemove', this.widtharg.widthmove); addListener(document, 'mouseup', this.widtharg.widthup); }, widthmove : function(e) { window.getSelection ? window.getSelection() .removeAllRanges() : document.selection.empty(); var x = e.clientX - this.widtharg.x, left = e.clientX, clientx = e.clientX; if (clientx < this.widtharg.x) { if (this.widtharg.x - clientx > this.widtharg.tdwidth - 35) left = this.widtharg.x - this.widtharg.tdwidth + 35; } if (clientx > this.widtharg.x) { if (clientx - this.widtharg.x > this.widtharg.nexttdwidth - 35) left = this.widtharg.x + this.widtharg.nexttdwidth - 35; } Css(this.line, { display : "block", left : left + "px" }); }, widthup : function(e) { this.line.style.display = "none"; var x = parseInt(this.line.style.left) - this.widtharg.x; this.widtharg.nexttd.style.width = this.widtharg.nexttdwidth - x + 'px'; this.widtharg.td.style.width = this.widtharg.tdwidth + x + 'px'; removeListener(document, 'mousemove', this.widtharg.widthmove); removeListener(document, 'mouseup', this.widtharg.widthup); }, closdrag : function(e) { e = e || window.event; var obj = e.srcElement || e.target; if (obj.nodeName.toLowerCase() == "span") obj = obj.parentNode; this.closarg.tdnum = obj.getAttribute('clos'); ; addListener(document, 'mousemove', this.closarg.closmove); addListener(document, 'mouseup', this.closarg.closup); }, closmove : function(e) { window.getSelection ? window.getSelection() .removeAllRanges() : document.selection.empty(); Css(this.img, { display : "block", left : e.clientX + 9 + "px", top : e.clientY + 20 + "px" }); }, closup : function() { this.img.style.display = "none"; removeListener(document, 'mousemove', this.closarg.closmove); removeListener(document, 'mouseup', this.closarg.closup); if (this.closarg.totdnum == this.closarg.tdnum) return; var rows = this.table.getElementsByTagName('tr'), tds, n, o; if ((parseInt(this.closarg.tdnum) + 1) == parseInt(this.closarg.totdnum)) { o = this.closarg.tdnum; n = this.closarg.totdnum; } else { n = this.closarg.tdnum; o = this.closarg.totdnum; } for (var i = 0, l = rows.length; i < l; i++) { tds = rows[i].getElementsByTagName('td'); try { rows[i].insertBefore(tds[n], tds[o]); } catch (err) { return; } } for (var i = 0, l = this.theadtds.length; i < l; i++) this.theadtds[i].setAttribute('clos', i); }, edit : function(e) { var o = e.srcElement || e.target; if (!o.getAttribute('edit')) return; this.inputtd = o; var v = o.innerHTML; o.innerHTML = ""; o.appendChild(this.input); this.input.value = v; this.input.focus(); }, save : function(o) { var edit = this.edits[o.parentNode.getAttribute('edit')]; if (edit.rule.test(this.input.value)) { this.inputtd.innerHTML = this.input.value; this.inputtd = null; } else { alert(edit.message); } }, sortTable : function(td, n, type) { var frag = document.createDocumentFragment(), str = td .getElementsByTagName('span')[0].innerHTML, span = td .getElementsByTagName('span')[0]; if (this.row != null || td == this.sortCol) { this.rows.reverse(); span.innerHTML = str.replace(/.$/, str .charAt(str.length - 1) == "↓" ? "↑" : "↓"); } else { this.rows.sort(this.compare(n, type)); span.innerHTML = span.innerHTML + "↑"; this.sortCol != null && (this.sortCol.getElementsByTagName('span')[0].innerHTML = this.sortCol .getElementsByTagName('span')[0].innerHTML .replace(/.$/, '')); } ; for (var i = 0, l = this.rows.length; i < l; i++) frag.appendChild(this.rows[i]); this.table.tBodies[0].appendChild(frag); if (Sys.IE6) { for ( var s in this.checkbox) this.checkbox[s].checked = true; } this.sortCol = td; }, compare : function(n, type) { return function(a1, a2) { var convert = { int : function(v) { return parseInt(v.replace(/,/g,'')) }, float : function(v) { return parseFloat(v) }, date : function(v) { return v.toString() }, string : function(v) { return v.toString() } }; !convert[type] && (convert[type] = function(v) { return v.toString() }); a1 = convert[type](a1.cells[n].innerHTML); a2 = convert[type](a2.cells[n].innerHTML); if (a1 == a2) return 0; return a1 < a2 ? -1 : 1; }; } }); var set = []; var obj = document.getElementById(table); var thead = obj.getElementsByTagName('thead')[0]; var tds = thead.getElementsByTagName('td'); var len = tds.length; for (var i = 0; i < len; i++) { var sort = tds[i].getAttribute('sort') || ''; var tmp = {}; if (sort != '') { // 去除空格 sort = sort.replace(/(^\s*)|(\s*$)/g, ""); tmp.id = i; tmp.type = sort; set.push(tmp); } ; } new Table($(table), set); }; /** * td内容过长处理 * * @param maxLength显示的最长的字符数 */ // class="min-25"的 // function tdTextLongHandle(maxLength){ // var text; // $(".min-25").each(function(){ // if($(this).children().length == 0){ // text = $(this).text().trim(); // if(text.length>maxLength){ // $("this,.min-25").addClass("min-30"); // // $(this).text(text.substring(0,maxLength)+"..."); // // $(this).prop("title",text); // } // } // }) // } // // class="min-20"的 // function tdTextLongHandl(maxLength){ // var text; // $(".min-20").each(function(){ // if($(this).children().length == 0){ // text = $(this).text().trim(); // if(text.length>maxLength){ // $("this,.min-20").addClass("min-25"); // // $(this).text(text.substring(0,maxLength)+"..."); // // $(this).prop("title",text); // } // } // }) // } // // class="min-15"的 // function tdTextLongHand(maxLength){ // var text; // $(".min-15").each(function(){ // if($(this).children().length == 0){ // text = $(this).text().trim(); // if(text.length>maxLength){ // $("this,.min-15").addClass("min-20"); // // $(this).text(text.substring(0,maxLength)+"..."); // // $(this).prop("title",text); // } // } // }) // } // $(document).ready(function(){ // tdTextLongHandle(23); // tdTextLongHandl(14); // tdTextLongHand(10); // }); // 表格隔列文字标题居右 // $(document).ready(function() { // $(".table6 tr td:even").addClass("td_right"); // }) $(function() { reloadTableEffect(); autoSetTbodyHeight(); loadThousandsSeparator(); }); /** * 重新加载表格效果 */ function reloadTableEffect() { trClick2Checked(); tableInterlaced(); tdTextLongHandle(); } /** * 表格隔行变色 */ function tableInterlaced() { $(".scrollContent tr").mouseover(function() { $(this).addClass("t3"); }).mouseout(function() { $(this).removeClass("t3"); }); $(".scrollContent tr:even").addClass("t2"); $(".scrollContent tr:odd").removeClass("t2"); } /** * 点击行选中复选框 */ function trClick2Checked() { if ($("tbody").hasClass("limit-box")) { } else { $(".scrollContent tr").unbind("click.trClickCheckBox"); $(".scrollContent tr").bind( "click.trClickCheckBox", function() { if ($(this).find("input[type='checkbox']").length > 0) { if ($(this).find("input[type='checkbox']").prop( "checked") == true) { $(this).find("input[type='checkbox']").prop( "checked", false); $(this).removeClass("bgss"); } else { $(this).find("input[type='checkbox']").prop( "checked", true); $(this).addClass("bgss"); } } }); $(".scrollContent tr input[type='text']").unbind("click.trClickCheckBox"); } } /** * 自动设置tbody的高度 */ function autoSetTbodyHeight() { // 根据屏幕分辨率不同给tbody加上合适的高度 if ($(".tbody").length == 0) return; var pageHeight = $(".tbody").offset().top; var total = document.documentElement.clientHeight; var colHeight = total - pageHeight - 30; $(".tbody").height(colHeight); } // 给id="tests"的tbody加上合适的高度使其出现纵向滚动条 total = document.documentElement.clientHeight; colHeight = total - 90; if ($("#tests").length > 0) { document.getElementById("tests").style.height = colHeight + "px"; } // 表格中文居左,数字居右 ; (function($) { setInterval(function() { $('.scrollContent td').each(function() { if (!isNaN($.trim($(this).text()))) { $(this).css("text-align", "right"); } else { $(this).css("text-align", "left"); } ; if (parseInt($(this).text()) > -1) { $(this).css("text-align", "right"); } else { $(this).css("text-align", "left"); } ; if (/[\u4e00-\u9fa5]/g.test($(this).text())) { $(this).css("text-align", "left"); } }); }, 10); }(jQuery)); /** * td内容过长处理 * * @param maxLength显示的最长的字节数 */ function tdTextLongHandle() { var text; var subText; var textLength; var maxLength; $("td[maxlength]:not([title])").each(function() { maxLength = Number($(this).attr("maxlength")); if (isNaN(maxLength) || maxLength <= 0) return true;// 不是数字类型或不大于0的直接返回 if ($(this).children().length == 0) { text = $(this).text(); textLength = text.replace(/[^\x00-\xff]/g, "**").length; if (textLength > maxLength) { $(this).text(autoAddEllipsis(text, maxLength)); $(this).prop("title", text); $(this).attr("data", text); } } }) } /** * 处理过长的字符串,截取并添加省略号 注:半角长度为1,全角长度为2 * * pStr:字符串 pLen:截取长度 * * return: 截取后的字符串 */ function autoAddEllipsis(pStr, pLen) { var _ret = cutString(pStr, pLen); var _cutFlag = _ret.cutflag; var _cutStringn = _ret.cutstring; if ("1" == _cutFlag) { return _cutStringn + "..."; } else { return _cutStringn; } } /** * 取得指定长度的字符串 注:半角长度为1,全角长度为2 * * pStr:字符串 pLen:截取长度 * * return: 截取后的字符串 */ function cutString(pStr, pLen) { // 原字符串长度 var _strLen = pStr.length; var _tmpCode; var _cutString; // 默认情况下,返回的字符串是原字符串的一部分 var _cutFlag = "1"; var _lenCount = 0; var _ret = false; if (_strLen <= pLen / 2) { _cutString = pStr; _ret = true; } if (!_ret) { for (var i = 0; i < _strLen; i++) { if (isFull(pStr.charAt(i))) { _lenCount += 2; } else { _lenCount += 1; } if (_lenCount > pLen) { _cutString = pStr.substring(0, i); _ret = true; break; } else if (_lenCount == pLen) { _cutString = pStr.substring(0, i + 1); _ret = true; break; } } } if (!_ret) { _cutString = pStr; _ret = true; } if (_cutString.length == _strLen) { _cutFlag = "0"; } return { "cutstring" : _cutString, "cutflag" : _cutFlag }; } /** * 判断是否为全角 * * pChar:长度为1的字符串 return: true:全角 false:半角 */ function isFull(pChar) { if ((pChar.charCodeAt(0) > 128)) { return true; } else { return false; } } $(document).ready(function(){ $("input[comma='comma_0']").blur(function() { $(this).val(parseFormatNum(parseFormatNums($(this).val(), 0), 0)) }) $("input[comma='comma_2']").blur(function() { $(this).val(parseFormatNum(parseFormatNums($(this).val(), 2), 2)) }) $("input[comma='comma_4']").blur(function() { $(this).val(parseFormatNum(parseFormatNums($(this).val(), 4), 4)) }) }); /** * 按照千位分隔符加载数据。 */ function loadThousandsSeparator() { $(".parseFormatNum_0").each(function() { if($(this).text()==''){}else{ $(this).text(parseFormatNum(parseFormatNums($(this).text(), 0), 0)) } }); $(".parseFormatNum_2").each(function() { if($(this).text()==''){}else{ $(this).text(parseFormatNum(parseFormatNums($(this).text(), 2), 2)) } }); $(".parseFormatNum_4").each(function() { if($(this).text()==''){}else{ $(this).text(parseFormatNum(parseFormatNums($(this).text(), 4), 4)) } }); /*初始化表单加逗号*/ $("input[comma='comma_0']").each(function() { if($(this).val()==''){}else{ $(this).val(parseFormatNum(parseFormatNums($(this).val(), 0), 0)); } }); $("input[comma='comma_2']").each(function() { if($(this).val()==''){}else{ $(this).val(parseFormatNum(parseFormatNums($(this).val(), 2), 2)); } }); $("input[comma='comma_4']").each(function() { if($(this).val()==''){}else{ $(this).val(parseFormatNum(parseFormatNums($(this).val(), 4), 4)); } }); } /** * 表单加逗号千位分隔符显示效果 */ function loadThousanq(){ $("input[comma='comma_0']").each(function() { if($(this).val()==''){}else{ $(this).val(parseFormatNum(parseFormatNums($(this).val(), 0), 0)); } }); $("input[comma='comma_2']").each(function() { if($(this).val()==''){}else{ $(this).val(parseFormatNum(parseFormatNums($(this).val(), 2), 2)); } }); $("input[comma='comma_4']").each(function() { if($(this).val()==''){}else{ $(this).val(parseFormatNum(parseFormatNums($(this).val(), 4), 4)); } }); } /** * 删除表单千位分隔符显示效果。 */ function removeps() { $("input[comma='comma_0']").each(function() { if($(this).val()==''){}else{ $(this).val(parseFormatNums($(this).val(), 0)) } }); $("input[comma='comma_2']").each(function() { if($(this).val()==''){}else{ $(this).val(parseFormatNums($(this).val(), 2)) } }); $("input[comma='comma_4']").each(function() { if($(this).val()==''){}else{ $(this).val(parseFormatNums($(this).val(), 4)) } }); } /** * 删除表格千位分隔符显示效果。 */ function removeparse() { $(".parseFormatNum_0").each(function() { if($(this).text()==''){}else{ $(this).text(parseFormatNums($(this).text(), 0)) } }); $(".parseFormatNum_2").each(function() { if($(this).text()==''){}else{ $(this).text(parseFormatNums($(this).text(), 2)) } }); $(".parseFormatNum_4").each(function() { if($(this).text()==''){}else{ $(this).text(parseFormatNums($(this).text(), 4)) } }); } // 金额加逗号 function parseFormatNum(num, n) { if(isNaN(num)){//js自己的方法检验数字 return 0; }else{ return num && num.toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) { return $1 + ","; }); } } // function parseFormatNum(number, n) { // if (n != 0) { // n = (n > 0 && n <= 20) ? n : 2; // } // number = parseFloat((number + "").replace(/[^\d\.-]/g, "")).toFixed(n) + ""; // var sub_val = number.split(".")[0].split("").reverse(); // var sub_xs = number.split(".")[1]; // var show_html = ""; // for (i = 0; i < sub_val.length; i++) { // show_html += sub_val[i] // + ((i + 1) % 3 == 0 && (i + 1) != sub_val.length ? "," : ""); // } // if (n == 0) { // return show_html.split("").reverse().join(""); // } else { // return show_html.split("").reverse().join("") + "." + sub_xs; // } // } // 金额去逗号 function parseFormatNums(number, n) { if (n != 0) { n = (n > 0 && n <= 20) ? n : 2; } number = parseFloat((number + "").replace(/[^\d\.-]/g, "")).toFixed(n) + ""; var sub_val = number.split(".")[0].split("").reverse(); var sub_xs = number.split(".")[1]; var show_html = ""; for (i = 0; i < sub_val.length; i++) { show_html += sub_val[i] + ((i + 1) % 3 == 0 && (i + 1) != sub_val.length ? "" : ""); } if (n == 0) { return show_html.split("").reverse().join(""); } else { return show_html.split("").reverse().join("") + "." + sub_xs; } } /** * 获取搜索条件的参数。 * @param formid * @returns */ function getSearchParams(){ var data = $('#pageForm').serializeArray(); for(var i=0;i<arguments.length;i++){ if(typeof(arguments[i]) != "string")continue; $("#"+arguments[i])[0].reset(); data = $.merge(data,$("#"+arguments[i]).serializeArray()); } return JSON.stringify(data); } /** * 获取搜索条件的参数。 * @param formid * @returns */ function getSearchParamsUnReset(){ var data = $('#pageForm').serializeArray(); for(var i=0;i<arguments.length;i++){ if(typeof(arguments[i]) != "string")continue; data = $.merge(data,$("#"+arguments[i]).serializeArray()); } return JSON.stringify(data); } /** * 返回列表页 */ function goBackList(url,data,method){ if( url ){ var form = $("<form></form>"); form.appendTo("body"); var inputs=""; var dataObj = JSON.parse(data); jQuery.each(dataObj, function(index,obj){ inputs+='<input type="hidden" name="'+ obj.name +'" value="'+ obj.value +'" />'; }); if(method==undefined)method = "GET"; form.html(inputs); form.prop("method",method); form.prop("action",url); showLoading(); form.submit(); }; } /** * 临时表单提交,编辑或新增时的页面跳转。 * @param url * @param paramString * @param method */ function tempFormSubmit(url,paramString,method,backUrl){ if( url ){ if(method==undefined)method = "GET"; var tempForm = document.createElement("form"); tempForm.id="tempForm1"; tempForm.method=method; tempForm.action=url; if(paramString){ var hideInput = document.createElement("input"); hideInput.type="hidden"; hideInput.name= "searchParams"; hideInput.value= paramString; tempForm.appendChild(hideInput); }; if(backUrl){ var hideInput = document.createElement("input"); hideInput.type="hidden"; hideInput.name= "backUrl"; hideInput.value= backUrl; tempForm.appendChild(hideInput); }; document.body.appendChild(tempForm); showLoading(); $(tempForm).submit(); document.body.removeChild(tempForm); }; }; 其中页面js里面,获取CheckBox已经勾选的对象数组函数getCheckBoxs()来自于checkBoxUtil.js //获得已经选中的checkBox,返回对象数组 function getCheckBoxs(name){ var count=0; var checkedArray = new Array(); var checkBoxs=document.getElementsByName(name); for (var i=0;i<checkBoxs.length;i++) { var e = checkBoxs[i]; if(e.checked){ checkedArray[count++]=checkBoxs[i]; } } return checkedArray; } 该js全文如下: //反选 function reverseCheck(name) { var eles=document.getElementsByName(name); for (var i=0;i<eles.length;i++) { var e = eles[i]; e.checked=!e.checked; } } //全不选 function unCheckAll(name) { var eles=document.getElementsByName(name); for (var i=0;i<eles.length;i++) { var e = eles[i]; e.checked=false; } } //全选 function checkAll(name) { var eles=document.getElementsByName(name); for (var i=0;i<eles.length;i++) { var e = eles[i]; e.checked=true; } } //获得已经选中的checkBox,返回对象数组 function getCheckBoxs(name){ var count=0; var checkedArray = new Array(); var checkBoxs=document.getElementsByName(name); for (var i=0;i<checkBoxs.length;i++) { var e = checkBoxs[i]; if(e.checked){ checkedArray[count++]=checkBoxs[i]; } } return checkedArray; } //获得已经选中的checkBox,返回对象数组 function ifChecked(name){ var checkBoxs=document.getElementsByName(name); for (var i=0;i<checkBoxs.length;i++) { var e = checkBoxs[i]; if(e.checked){ return true; } } return false; } //获得未选中的checkBox,返回对象数组 function getUnCheckBoxs(name){ var count=0; var uncheckedArray = new Array(); var checkBoxs=document.getElementsByName(name); for (var i=0;i<checkBoxs.length;i++) { var e = checkBoxs[i]; if(!e.checked){ uncheckedArray[count++]=checkBoxs[i]; } } return uncheckedArray; } //设置选中值 function checkBoxs(name,matchFunction){ if(!matchFunction&&typeof(matchFunction)!="function"){ alert('没有实现匹配方法!'); return; } var checkBoxs=document.getElementsByName(name); for (var i=0;i<checkBoxs.length;i++) { var e = checkBoxs[i]; if(matchFunction(checkBoxs[i])){ checkBoxs[i].checked=true; } } } //设置复选框状态 function setCheckBoxs(name,matchFunction){ if(!matchFunction&&typeof(matchFunction)!="function"){ alert('没有实现匹配方法!'); return; } var checkBoxs=document.getElementsByName(name); for (var i=0;i<checkBoxs.length;i++) { var e = checkBoxs[i]; if(matchFunction(checkBoxs[i])){ checkBoxs[i].disabled=true; } } } //获得已经选中的checkBox,返回以两个指定列的值组成的二维数组 function getCheckBoxsMap(name, value){ var checkedArray = new Array(); var checkBoxs=document.getElementsByName(name); var checkValues=document.getElementsByName(value); var count=0; //生成第一维,必须先声明第一维,然后才可以声明第二维,声明时,用checkedArray[count++]失败 for (var i=0;i<checkBoxs.length;i++){ var e = checkBoxs[i]; if(e.checked){ checkedArray[count] = new Array(); checkedArray[count][0]=checkBoxs[i].value; checkedArray[count][1]=checkValues[i].value; count ++; } } //for (var k=0;k<checkedArray.length;k++){ // alert(checkedArray[k][0] + " --- " + checkedArray[k][1]); //} return checkedArray; } //隐藏复选框 function hideCheckBoxs(name,matchFunction){ if(!matchFunction&&typeof(matchFunction)!="function"){ alert('没有实现匹配方法!'); return; } var checkBoxs=document.getElementsByName(name); var objAry = new Array(); for (var i=0;i<checkBoxs.length;i++) { if(matchFunction(checkBoxs[i])){ objAry[objAry.length] = checkBoxs[i]; } } for (var j=0;j<objAry.length;j++) { objAry[j].outerHTML = ""; } } 自定义的弹出格式方法来自另一个js文件(modalEffects.js),全文如下: /** * modalEffects.js v1.0.0 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2013, Codrops * http://www.codrops.com */ // 弹窗定位 function yyi(obj,offset){ var objClass = obj.class; var top; var left; if($(obj).hasClass("md-modal")){ top = ($(window).height() - $('#'+obj.id).height())/2; left = ($(window).width() - $('#'+obj.id).width())/2; } if($(obj).hasClass("md-tree")){ top = ($(window).height() - $('#'+obj.id).height())/2; left = ($(window).width() - $('#'+obj.id).width())/1.12; } if($(obj).hasClass("md-treeqw")){ var ssd = offset.top+30; var qqd = offset.left; top = ssd; left = qqd; } var scrollTop = $(document).scrollTop(); var scrollLeft = $(document).scrollLeft(); $('#'+obj.id).css( { position : 'absolute', top : top + scrollTop, left : left + scrollLeft} ); } var ModalEffects = (function() { function init() { //var overlay = document.querySelector( '.md-overlay' ); [].slice.call( document.querySelectorAll( '.md-trigger' ) ).forEach( function( el, i ) { var modal = document.querySelector( '#' + el.getAttribute( 'data-modal' ) ), close = modal.querySelector( '.md-close' ); close1 = modal.querySelector( '.abc' ); close2 = modal.querySelector( '.asd' ); function removeModal( hasPerspective ) { classie.remove( modal, 'md-show' ); if( hasPerspective ) { classie.remove( document.documentElement, 'md-perspective' ); } } function removeModalHandler() { removeModal( classie.has( el, 'md-setperspective' ) ); } el.addEventListener('click', function(ev) { classie.add(modal, 'md-show'); yyi(modal,$(el).offset()); // overlay.removeEventListener( 'click', removeModalHandler ); // overlay.addEventListener( 'click', removeModalHandler ); // 拖拽 var oTitle = modal.getElementsByTagName("h3")[0]; var oDrag = new Drag(modal, { handle: oTitle, limit: false }); // end--- if (classie.has(el, 'md-setperspective')) { setTimeout(function() { classie.add(document.documentElement, 'md-perspective'); }, 25); } }); close.addEventListener( 'click', function( ev ) { ev.stopPropagation(); removeModalHandler(); }); if(close1!=null){ close1.addEventListener( 'click', function( ev ) { ev.stopPropagation(); removeModalHandler(); }); } if(close2!=null){ close2.addEventListener( 'click', function( ev ) { ev.stopPropagation(); removeModalHandler(); }); } } ); } init(); })(); //弹窗拖拽 function Drag() { //初始化 this.initialize.apply(this, arguments) } Drag.prototype = { //初始化 initialize: function(drag, options) { this.drag = this.$(drag); this._x = this._y = 0; this._moveDrag = this.bind(this, this.moveDrag); this._stopDrag = this.bind(this, this.stopDrag); this.setOptions(options); this.handle = this.$(this.options.handle); this.maxContainer = this.$(this.options.maxContainer); this.maxTop = Math.max(this.maxContainer.clientHeight, this.maxContainer.scrollHeight) - this.drag.offsetHeight; this.maxLeft = Math.max(this.maxContainer.clientWidth, this.maxContainer.scrollWidth) - this.drag.offsetWidth; this.limit = this.options.limit; this.lockX = this.options.lockX; this.lockY = this.options.lockY; this.lock = this.options.lock; this.onStart = this.options.onStart; this.onMove = this.options.onMove; this.onStop = this.options.onStop; this.handle.style.cursor = "move"; this.changeLayout(); this.addHandler(this.handle, "mousedown", this.bind(this, this.startDrag)) }, changeLayout: function() { this.drag.style.top = this.drag.offsetTop + "px"; this.drag.style.left = this.drag.offsetLeft + "px"; this.drag.style.position = "absolute"; this.drag.style.margin = "0" }, startDrag: function(event) { var event = event || window.event; this._x = event.clientX - this.drag.offsetLeft; this._y = event.clientY - this.drag.offsetTop; this.addHandler(document, "mousemove", this._moveDrag); this.addHandler(document, "mouseup", this._stopDrag); event.preventDefault && event.preventDefault(); this.handle.setCapture && this.handle.setCapture(); this.onStart() }, moveDrag: function(event) { var event = event || window.event; var iTop = event.clientY - this._y; var iLeft = event.clientX - this._x; if (this.lock) return; this.limit && (iTop < 0 && (iTop = 0), iLeft < 0 && (iLeft = 0), iTop > this.maxTop && (iTop = this.maxTop), iLeft > this.maxLeft && (iLeft = this.maxLeft)); this.lockY || (this.drag.style.top = iTop + "px"); this.lockX || (this.drag.style.left = iLeft + "px"); event.preventDefault && event.preventDefault(); this.onMove() }, stopDrag: function() { this.removeHandler(document, "mousemove", this._moveDrag); this.removeHandler(document, "mouseup", this._stopDrag); this.handle.releaseCapture && this.handle.releaseCapture(); this.onStop() }, //参数设置 setOptions: function(options) { this.options = { handle: this.drag, //事件对象 limit: true, //锁定范围 lock: false, //锁定位置 lockX: false, //锁定水平位置 lockY: false, //锁定垂直位置 maxContainer: document.documentElement || document.body, //指定限制容器 onStart: function() {}, //开始时回调函数 onMove: function() {}, //拖拽时回调函数 onStop: function() {} //停止时回调函数 }; for (var p in options) this.options[p] = options[p] }, //获取id $: function(id) { return typeof id === "string" ? document.getElementById(id) : id }, //添加绑定事件 addHandler: function(oElement, sEventType, fnHandler) { return oElement.addEventListener ? oElement.addEventListener(sEventType, fnHandler, false) : oElement.attachEvent("on" + sEventType, fnHandler) }, //删除绑定事件 removeHandler: function(oElement, sEventType, fnHandler) { return oElement.removeEventListener ? oElement.removeEventListener(sEventType, fnHandler, false) : oElement.detachEvent("on" + sEventType, fnHandler) }, //绑定事件到对象 bind: function(object, fnHandler) { return function() { return fnHandler.apply(object, arguments) } } }; // 采购合同号录入 $(document).ready(function(){ $('#addradio').click(function(){ $('.cghth:checked').closest('tr').find('td').each(function(){ var id = $(this).attr('data-id'); $('#'+id).val($.trim($(this).text())); }); }); }); // 商品录入 $(document).ready(function(){ $('#addsplrr').click(function(){ $('.splrr:checked').closest('tr').find('td').each(function(){ var id = $(this).attr('data-id'); $('#'+id).val($.trim($(this).text())); }); }); }); // 商品录入2 $(document).ready(function(){ $('#addsplrrr').click(function(){ $('.splrrr:checked').closest('tr').find('td').each(function(){ var id = $(this).attr('data-id'); $('#'+id).val($.trim($(this).text())); }); }); }); // 品牌录入 $(document).ready(function(){ $('#addpp').click(function(){ $('.pplr:checked').closest('tr').find('td').each(function(){ var id = $(this).attr('data-id'); $('#'+id).val($.trim($(this).text())); }); }); }); // 品牌录入2 $(document).ready(function(){ $('#addppp').click(function(){ $('.pplr1:checked').closest('tr').find('td').each(function(){ var id = $(this).attr('data-id'); $('#'+id).val($.trim($(this).text())); }); }); }); // 供应商录入 $(document).ready(function(){ $('#addgys').click(function(){ $('.gyslr:checked').closest('tr').find('td').each(function(){ var id = $(this).attr('data-id'); $('#'+id).val($.trim($(this).text())); }); }); }); // 公司录入 $(document).ready(function(){ $('#addgs').click(function(){ $('.gslr:checked').closest('tr').find('td').each(function(){ var id = $(this).attr('data-id'); $('#'+id).val($.trim($(this).text())); }); }); }); // 仓库录入 $(document).ready(function(){ $('#addcklr').click(function(){ $('.cklr:checked').closest('tr').find('td').each(function(){ var id = $(this).attr('data-id'); $('#'+id).val($.trim($(this).text())); }); }); }); // input验证手机(一部手机) function checkMobile(input) { var re = /^0?1[2|3|4|5|6|7|8|9][0-9]\d{8}$/; var value = input.value; if (value == '') {} else if (re.test(value)) {} else { SimplePop.alert("手机号码格式不正确!"); $(input).val(""); } } //两部手机 function checkMobile1(input) { var re = /^0?1[2|3|4|5|6|7|8|9][0-9]\d{8}$/; var value = input.value; var s=""; if(value.length>11){ s = value.indexOf(","); } if(s==-1){ SimplePop.alert("多个电话号码之间用英文“,”隔开!"); $(input).val(""); return false; } if(value == ''){}else if(value.length==11){ if(re.test(value)){}else{ SimplePop.alert("手机号码格式不正确!"); $(input).val(""); } }else{ if(re.test(value.substring(0,11)) && re.test(value.substring(12))){ }else{ SimplePop.alert("手机号码格式不正确!"); $(input).val(""); } } } // input验证电话号码(固定电话) function checkPhone(input) { var re = /^0\d{2,3}-?\d{7,8}$/ var value = input.value; if (value == '') {} else if (re.test(value)) {} else { SimplePop.alert("电话号码格式不正确!(区号+号码,区号以0开头,3位或4位)"); $(input).val(""); } } // input验证邮箱 function checkEmail(input) { var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/ var value = input.value; if (value == '') {} else if (re.test(value)) {} else { SimplePop.alert("邮箱格式错误!"); $(input).val(""); } } // 显示加载中 function showLoading(){ // 添加遮罩层 $('.overlay').remove(); $('body').append('<div class="overlay"></div>'); $(".overlay").css({'position':'fixed','top':'0','right':'0','bottom':'0','left':'0','z-index':'9998','width':'100%','height':'100%'}); $(".overlay").css({'_padding':'0 20px 0 0','background':'#f6f4f5','display':'none'}); $(".overlay").css({'display':'block','opacity':'0.8'}); var h = $(document).height(); $(".overlay").css({"height": h }); // 添加提示层 $('#AjaxLoading').remove(); $('body').append('<div id="AjaxLoading" class="showbox"><div class="loadingWord"><img src="../resources/core/backgrounds/waiting.gif">加载中,请稍候...</div></div>'); $('#AjaxLoading').css({'border':'1px solid #8CBEDA','color':'#37a','font-size':'12px','font-weight':'bold'}); $('#AjaxLoading .loadingWord').css({'width':'180px','line-height':'50px','border':'2px solid #D6E7F2','background':'#fff'}); $('#AjaxLoading img').css({'margin':'10px 15px','float':'left','display':'inline'}); $('.showbox').css({'position':'fixed','top':'300px','left':'50%','z-index':'9999','opacity':'0','filter':'alpha(opacity=0)','margin-left':'-80px'}); $(".overlay,.showbox").css({'position':'absolute','top':'expression(eval(document.documentElement.scrollTop))'}); $(".showbox").stop(true).animate({'opacity':'1'},200); } // 隐藏加载中 function clearLoading(){ $(".showbox").stop(true).animate({'opacity':'0'},400); $(".overlay").css({'display':'none','opacity':'0'}); $("#AjaxLoading").css({'display':'none','opacity':'0'}); } $(document).ready(function(){ $(".action").click(function(){ showLoading(); setTimeout(function(){ clearLoading(); },800); }); }); // input输入框输入限制 $(document).ready(function(){ //输入数字自动添加小数点后1位 $(".e_de1").change(function(){ if(this.value.indexOf('.')==-1&&this.value!=''){ this.value+='.0'; } }); //输入数字自动添加小数点后2位 $(".e_de2").change(function(){ if(this.value.indexOf('.')==-1&&this.value!=''){ this.value+='.00'; } }); //输入数字自动添加小数点后3位 $(".e_de3").change(function(){ if(this.value.indexOf('.')==-1&&this.value!=''){ this.value+='.000'; } }); //输入数字自动添加小数点后4位 $(".e_de4").change(function(){ if(this.value.indexOf('.')==-1&&this.value!=''){ this.value+='.0000'; } }); //输入数字自动添加小数点后5位 $(".e_de5").change(function(){ if(this.value.indexOf('.')==-1&&this.value!=''){ this.value+='.00000'; } }); //输入数字自动添加小数点后6位 $(".e_de6").change(function(){ if(this.value.indexOf('.')==-1&&this.value!=''){ this.value+='.000000'; } }); //输入数字自动添加小数点后7位 $(".e_de7").change(function(){ if(this.value.indexOf('.')==-1&&this.value!=''){ this.value+='.0000000'; } }); //输入数字自动添加小数点后8位 $(".e_de8").change(function(){ if(this.value.indexOf('.')==-1&&this.value!=''){ this.value+='.00000000'; } }); //输入数字自动添加小数点后9位 $(".e_de9").change(function(){ if(this.value.indexOf('.')==-1&&this.value!=''){ this.value+='.000000000'; } }); $(".e_de1,.e_de2,.e_de3,.e_de4,.e_de5,.e_de6,.e_de7,.e_de8,.e_de9").keyup(function(){ var tmptxt = $(this).val(); $(this).val(tmptxt.replace(/[^(\d|\.)]/g, '')); }); //文本框只能输入数字 $("input[class='e_number']").keyup(function() { var tmptxt = $(this).val(); $(this).val(tmptxt.replace(/[^\(\d|\.)]/g, '')); }).bind("paste", function() { var el = $(this); setTimeout(function() { var text = $(el).val(); el.val(text.replace(/[^\(\d|\.)]/g, '')); }, 100); // var tmptxt = $(this).val(); // $(this).val(tmptxt.replace(/[^(\d|\.)]/g, '')); }).css("ime-mode", "disabled"); //文本框只能输入数字(可以负数) $("input[class='e_number_e']").keyup(function() { var tmptxt = $(this).val(); $(this).val(tmptxt.replace(/[^\-?(\d|\.)]/g, '')); }).bind("paste", function() { var el = $(this); setTimeout(function() { var text = $(el).val(); el.val(text.replace(/[^\-?(\d|\.)]/g, '')); }, 100); // var tmptxt = $(this).val(); // $(this).val(tmptxt.replace(/[^(\d|\.)]/g, '')); }).css("ime-mode", "disabled"); //文本框只能输入数字和英文(禁止输入中文) $("input[class='e_inqqrqw']").keyup(function() { var tmptxt = $(this).val(); $(this).val(tmptxt.replace(/[\W]/g,'')); }).bind("paste", function() { var el = $(this); setTimeout(function() { var text = $(el).val(); el.val(text.replace(/[\W]/g,'')); }, 100); // var tmptxt = $(this).val(); // $(this).val(tmptxt.replace(/[\W]/g,'')); }).css("ime-mode", "disabled"); //inupt只能输入整数 $("input[class='e_integer']").keyup(function() { if(this.value.length==1){ this.value=this.value.replace(/[^1-9]/g,'') }else{ this.value=this.value.replace(/\D/g,'') } }); //文本框只能输入大于0(不包括0)的正数 $("input[class='e_greater']").keyup(function() { var tmptxt = $(this).val(); $(this).val(tmptxt.replace(/^[^1-9]/, '')); }).bind("paste", function() { var el = $(this); setTimeout(function() { var text = $(el).val(); el.val(text.replace(/[^\d\.]/g, '')); }, 100); // var tmptxt = $(this).val(); // $(this).val(tmptxt.replace(/[^\d\.]/g, '')); }).css("ime-mode", "disabled"); $("input[class='e_greater']").keyup(function() { var tmptxt = $(this).val(); $(this).val(tmptxt.replace(/[^\d\.]/g, '')); }); //文本框只能输入英文字母 $("input[class='e_nber']").keyup(function() { var tmptxt = $(this).val(); $(this).val(tmptxt.replace(/[^\a-zA-Z]/g,'')); }).bind("paste", function() { var el = $(this); setTimeout(function() { var text = $(el).val(); el.val(text.replace(/[^\a-zA-Z]/g,'')); }, 100); // var tmptxt = $(this).val(); // $(this).val(tmptxt.replace(/[^\a-zA-Z]/g,'')); }).css("ime-mode", "disabled"); //inupt只能输入负数 $("input[class='e_inr']").keyup(function() { var tmptxt = $(this).val(); $(this).val(tmptxt.replace(/^[^1-9][\d]?$/, '')); if (!isNaN(this.value)) { if (this.value > 0) { this.value = 0-this.value; }; } else { this.value = ''; }; }) //inupt只能输入负数和0 $("input[class='e_inrqw']").keyup(function() { var tmptxt = $(this).val(); if (!isNaN(this.value)) { if (this.value > 0) { this.value = 0-this.value; }; } else { this.value = ''; }; }) ////清除文本框里的空格 // $("input").keyup(function() { // var tmptxt = $(this).val(); // $(this).val(tmptxt.replace(/[ ]/g,'')); // }) }); //input只能输入1位小数点 function e_limit1(obj){ if(obj.value==obj.value2) return; if(obj.value.search(/^\d*(?:\.\d{0,1})?$/)==-1) obj.value=(obj.value2)?obj.value2:''; else obj.value2=obj.value; } //input只能输入2位小数点 function e_limit2(obj){ if(obj.value==obj.value2) return; if(obj.value.search(/^\d*(?:\.\d{0,2})?$/)==-1) obj.value=(obj.value2)?obj.value2:''; else obj.value2=obj.value; } //input只能输入3位小数点 function e_limit3(obj){ if(obj.value==obj.value2) return; if(obj.value.search(/^\d*(?:\.\d{0,3})?$/)==-1) obj.value=(obj.value2)?obj.value2:''; else obj.value2=obj.value; } //input只能输入4位小数点 function e_limit4(obj){ if(obj.value==obj.value2) return; if(obj.value.search(/^\d*(?:\.\d{0,4})?$/)==-1) obj.value=(obj.value2)?obj.value2:''; else obj.value2=obj.value; } // 时间控件--年月日 $(document).ready(function(){ $('.e_ymd').focus(function(){ WdatePicker({ dateFmt:'yyyy-MM-dd', }); }); }); // 时间控件--年月日时分秒 $(document).ready(function(){ $('.e_ymdhms').focus(function(){ WdatePicker({ dateFmt:'yyyy-MM-dd HH:mm:ss', }); }); }); $(document).ready(function() { $('.e_yyyy').focus(function() { WdatePicker({ dateFmt : 'yyyy', }); }); }); $(document).ready(function() { $('.e_MM').focus(function() { WdatePicker({ dateFmt : 'MM', }); }); }); //input字段不能为空或者值超出最大值 function cchecked(id){ if(!checkEmpty(id))return false; if(!checkMaxNumberLength(id))return false; return true; } function checkEmpty(id){ var num=0; var str=""; var name=""; $("#"+id).find("input[type$='text'][msgg]").each(function(n){ if($(this).val()=="") { num++; str+=$(this).attr("msgg")+"不能为空!\r\n"; } }); $("#"+id).find("select[msgg]").each(function(n){ if($(this).val()=="") { num++; str+=$(this).attr("msgg")+"不能为空!\r\n"; } }); if(num>0){ SimplePop.alert(str); return false; } else{ return true; } } function checkMaxNumberLength(id){ var str=""; var value=0; var length = 0; var objStr = ""; var maxnum = 0; $("#"+id).find("input[maxnumLength]").each(function(n){ length = Number($(this).attr("maxnumLength")); value = Number(conver2number($(this).val())); objStr = $(this).attr("msg"); objStr = objStr == undefined?$(this).attr("msgg"):objStr; objStr = objStr == undefined?$(this).parent().prev().text():objStr; objStr = objStr == undefined?$(this).attr("name"):objStr; if(isNaN(value)){ str += objStr+"应为整数位不大于"+length+"位以内的数字!\r\n"; return true; } if(!isNaN(length)){ maxnum = Math.pow(10,length); if(value>=maxnum||value<=(0-maxnum)){ str += objStr+"的值,整数位有效数字超出"+length+"位,无法保存!\r\n"; } } }); if(str.length>0){ SimplePop.alert(str); return false; } return true; } /** * 转数字 */ function conver2number(num,replaceValue){ num = Number(num.replace(/,/gi,'')); if(isNaN(num)){ if(replaceValue!=undefined){ return replaceValue; } return 0 }else{ return num; } } /* * * jQuery SimplePop * IE 7+ * @date 2014-11-24 13:19:36 * https://www.sucaijiayuan.com * */ // 温馨提示消息弹窗js "use strict"; var SimplePop = { alert: function(msg, arg) { var alertDefaults = { popType: "alert", title: "温馨提示", content: "<div class='layer_msg'><p>" + (msg === undefined ? "" : msg) + "</p><button id='simplePopBtnSure' type='button'>确定</button></div>", callback: function() { } }; var opt = $.extend({}, this._defaults, alertDefaults, arg); this._creatLayer(opt) }, confirm: function(msg, arg) { var confirmDefaults = { popType: "confirm", title: "温馨提示", content: "<div class='layer_msg'><p>" + (msg === undefined ? "" : msg) + "</p><button id='simplePopBtnSure' type='button'>确定</button><button id='SimplePopBtncancel' type='button'>取消</button></div>", cancel: function() { }, confirm: function() { } }; var opt = $.extend({}, this._defaults, confirmDefaults, arg); this._creatLayer(opt) }, prompt: function(msg, arg) { var promptDefaults = { popType: "prompt", title: "温馨提示", content: "<div class='layer_msg'><p>" + (msg === undefined ? "" : msg) + "</p><div><input type='text' /></div><button id='simplePopBtnSure' type='button'>确定</button><button id='SimplePopBtncancel' type='button'>取消</button></div>", cancel: function() { }, confirm: function(value) { } }; var opt = $.extend({}, this._defaults, promptDefaults, arg); this._creatLayer(opt) }, closeSimplePop: function() { this._closeLayer(); }, _defaults: { icon: "", title: "", content: "", width: 0, height: 0, background: "#000", opacity: 0.5, duration: "normal", showTitle: true, escClose: true, popMaskClose: false, drag: true, dragOpacity: 1, popType: "alert", type: "info" }, _creatLayer: function(opt) { var self = this; $(".popMask").empty().remove(); $(".popMain").empty().remove(); $("body").append("<div class='popMask'></div>"); var $mask = $(".popMask"); $mask.css({ "background-color": opt.background, filter: "alpha(opacity=" + opt.opacity * 100 + ")", "-moz-opacity": opt.opacity, opacity: opt.opacity }); opt.popMaskClose && $mask.bind("click", function() { self._closeLayer() }); opt.escClose && $(document).bind("keyup", function(e) { try { e.keyCode == 27 && self._closeLayer() } catch (f) { self._closeLayer() } }); $mask.fadeIn(opt.duration); var wrap = "<div class='popMain'>"; wrap += "<div class='popTitle'>" + (opt.icon !== undefined && opt.icon !== "" ? "<img class='icon' src='" + opt.icon + "' />" : "") + "<span class='text'>" + opt.title + "</span><span class='close'>×</span></div>"; wrap += "<div class='popContent'>" + opt.content + "</div>"; wrap += "</div>"; $("body").append(wrap); var $popMain = $(".popMain"); $popMain.find('.layer_msg').addClass(opt.type + '_icon') var $popTitle = $(".popTitle"); var $popContent = $(".popContent"); opt.showTitle ? $popTitle.show() : $popTitle.hide(); opt.width !== 0 && $popTitle.width(opt.width); $(".popTitle .close").bind("click", function() { $mask.fadeOut(opt.duration); $popMain.fadeOut(opt.duration); $popMain.attr("isClose", "1"); opt.type == "container" && $(opt.targetId).empty().append(opt.content); }); opt.width !== 0 && $popContent.width(opt.width); opt.height !== 0 && $popContent.height(opt.height); $popMain.css({ left: $(window).width() / 2 - $popMain.width() / 2 + "px", top: $(window).height() / 2 - $popMain.height() / 2 + "px" }); $(window).resize(function() { $popMain.css({ left: $(window).width() / 2 - $popMain.width() / 2 + "px", top: $(window).height() / 2 - $popMain.height() / 2 + "px" }) }); opt.drag && this._drag(opt.dragOpacity) switch (opt.popType) { case "alert": $popMain.fadeIn(opt.duration, function() { $popMain.attr("style", $popMain.attr("style").replace("FILTER:", "")) }); $("#simplePopBtnSure").bind("click", function() { opt.callback(); self._closeLayer() }); break; case "confirm": $popMain.fadeIn(opt.duration, function() { $popMain.attr("style", $popMain.attr("style").replace("FILTER:", "")) }); $("#simplePopBtnSure").bind("click", function() { opt.confirm() self._closeLayer() }); $("#SimplePopBtncancel").bind("click", function() { opt.cancel() self._closeLayer() }); break; case "prompt": $popMain.fadeIn(opt.duration, function() { $popMain.attr("style", $popMain.attr("style").replace("FILTER:", "")) }); $("#simplePopBtnSure").bind("click", function() { opt.confirm($(".layer_msg input").val()) self._closeLayer() }); $("#SimplePopBtncancel").bind("click", function() { opt.cancel() self._closeLayer() }); break; default: break; } }, _closeLayer: function() { $(".popTitle .close").triggerHandler("click") }, _drag: function(d) { var isDown = false, b, g; $(".popTitle").bind("mousedown", function(e) { if ($(".popMain:visible").length > 0) { isDown = true; b = e.pageX - parseInt($(".popMain").css("left"), 10); g = e.pageY - parseInt($(".popMain").css("top"), 10); $(".popTitle").css({ cursor: "move" }) } }); $(document).bind("mousemove", function(e) { if (isDown && $(".popMain:visible").length > 0) { d != 1 && $(".popMain").fadeTo(0, d); var f = e.pageX - b; e = e.pageY - g; if (f < 0) f = 0; if (f > $(window).width() - $(".popMain").width()) f = $(window).width() - $(".popMain").width() - 2; if (e < 0) e = 0; if (e > $(window).height() - $(".popMain").height()) e = $(window).height() - $(".popMain").height() - 2; $(".popMain").css({ top: e, left: f }) } }).bind("mouseup", function() { if ($(".popMain:visible").length > 0) { isDown = false; d != 1 && $(".popMain").fadeTo(0, 1); $(".popTitle").css({ cursor: "auto" }) } }) } } function SimplePopConfirm(msg,funSimp){ SimplePop.confirm(msg,{ type: "error", cancel: function(){ }, //确定按钮回调 confirm: function(){ funSimp(); } }); } function SimplePop4Confirm(msg,Func){ var args = new Array(); for(i=2;i<arguments.length;i++){ args[i-2] =arguments[i]; } SimplePop.confirm(msg,{ type: "info", confirm: function(){ Func(args); } }) } 相关文章【JavaScript】checkBox的多选行信息获取上一篇:Android开发之扫描附近wifi热点并列表显示下一篇:Flask实战-留言板-安装虚拟环境、使用包组织代码