第一种:
JS复选框向一个文本框中传值的多选效果 input { margin-right: 3px } label { margin: 0 5px } window.onload = function () { var obox = document.getElementById("box"); var cboList = obox.getElementsByTagName("input"); var oText = document.getElementById("tt"); document.getElementById("box").onclick = function (e) { var src = e ? e.target : event.srcElement; if (src.tagName == "INPUT") { var values = []; for (var i = 0; i < cboList.length; i++) { if (cboList[i].checked) {values.push(cboList[i].value); } } oText.value = values.join(","); } } }
第二种:
原生js实现多选功能 HTML CSS Javascript vue react
/*基本思路: 1、创建一个隐藏的option,添加到select的最后; 2、每次选中的值都存入这个option,如果已经选中,当再次选择时,就会删掉; 3、若已选择了值,就将隐藏的option的selected属性设置为true,以便获取多选内容 */ let values = []; //存储选择的内容 let opts = []; //存储option标签 let select = document.getElementById("multipleSelect"); for(let i=0;i-1){ //若已选择,就删除该选择,并且将option的背景恢复为未被选择的状态 values.splice(index,1); opts.filter(function (opt){ if(opt.value === value){ opt.style=""; } }); }else {//没选择就将该值push到values中 values.push(value); }; this.options[this.length-1].text=values.toString(); //将values数组中的数据转化成字符串的格式赋给隐藏的option if(values.length>0){ //将隐藏的option的selected属性设置为true,这样select.value获取的值就是多选选中的值 this.options[this.length-1].selected=true; }else { this.options[0].selected=true; } console.log(select.value);// 打印多选的内容 });
第三种:
(function () { selectMultip = { register: function (id) { //大致思路是:为下拉选创建一个隐藏的子选项,每次单选之后将单选的值追加到隐藏的子选项中,并将子选项选中显示即可 //全局查找所有标记multip的select document.querySelectorAll("[multip]").forEach(function (e) { render(e); }) }, reload: function (id, data, setData) { var htm = ""; for (var i = 0; i < data.length; i++) { htm += '' + data[i].text + '' } var e = document.getElementById(id); e.innerHTML = htm; render(e); this.setVal(id, setData); }, setVal: function (id, str) { var type = Object.prototype.toString.call(str); switch (type) { case "[object String]":document.getElementById(id).val = str;break; case "[object Array]":document.getElementById(id).val = str.toString();break; default:break; } }, getVal: function (id) { return document.getElementById(id).val; }, } function render(e) { e.param = { arr: [], valarr: [], opts: [] }; var choosevalue = "", op; for (var i = 0; i < e.length; i++) { op = e.item(i); e.param.opts.push(op); if (op.hasAttribute("choose")) { if (choosevalue == "") {choosevalue = op.value } else {choosevalue += "," + op.value; } } } //创建一个隐藏的option标签用来存储多选的值,其中的值为一个数组 var option = document.createElement("option"); option.hidden = true; e.appendChild(option); e.removeEventListener("input", selchange); e.addEventListener("input", selchange); //重新定义标签基础属性的get和set方法,实现取值和赋值的功能 Object.defineProperty(e, "val", { get: function () { return this.querySelector("[hidden]").value; }, set: function (value) { e.param.valarr = []; var valrealarr = value == "" ? [] : value.split(","); e.param.arr = []; e.param.opts.filter(function (o) {o.style = ""; }); if (valrealarr.toString()) {for (var i = 0; i < valrealarr.length; i++) { e.param.opts.filter(function (o) { if (o.value == valrealarr[i]) { o.style = "color: blue;"; e.param.arr.push(o.text); e.param.valarr.push(o.value) } });}this.options[e.length - 1].text = e.param.arr.toString();this.options[e.length - 1].value = e.param.valarr.toString();this.options[e.length - 1].selected = true; } else {this.options[0].selected = true; } }, configurable: true }) //添加属性choose 此属性添加到option中用来指定默认值 e.val = choosevalue; //添加属性tip 此属性添加到select标签上 if (e.hasAttribute("tip") && !e.tiped) { e.tiped = true; e.insertAdjacentHTML('afterend', '*可多选'); } } function selchange() { var text = this.options[this.selectedIndex].text; var value = this.options[this.selectedIndex].value; this.options[this.selectedIndex].style = "color: blue;"; var ind = this.param.arr.indexOf(text); if (ind > -1) { this.param.arr.splice(ind, 1); this.param.valarr.splice(ind, 1); this.param.opts.filter(function (o) { if (o.value == value) {o.style = ""; } }); } else { this.param.arr.push(text); this.param.valarr.push(value); } this.options[this.length - 1].text = this.param.arr.toString(); this.options[this.length - 1].value = this.param.valarr.toString(); if (this.param.arr.length > 0) { this.options[this.length - 1].selected = true; } else { this.options[0].selected = true; } } })(); 文本框下拉单选多选 ---请选择--- 桃子 大苹果 樱桃 草莓 ---请选择--- 板凳 椅子 桌子 书架 selectMultip.register();
第四种:
摘自文章:https://www.jb51.net/article/88573.htm
下拉框中的复选框 function aa(obj, td_name) { var select_value = document.getElementById("where"); var td_value = document.getElementById(td_name); if (obj.checked == true) { td_value.className = 'c1'; //选中时颜色 if (select_value.value.length > 0) { select_value.value += "," + td_value.innerText; } else { select_value.value += td_value.innerText; } } else { td_value.className = 'c0'; //取消时颜色 if (select_value.value.indexOf("," + td_value.innerText + ",") != -1) { select_value.value = select_value.value.replace("," + td_value.innerText, ''); } else if (select_value.value.indexOf("," + td_value.innerText) != -1) { select_value.value = select_value.value.replace("," + td_value.innerText, ''); } else if (select_value.value.indexOf(td_value.innerText + ",") != -1) { select_value.value = select_value.value.replace(td_value.innerText + ",", ''); } else if (select_value.value.indexOf(td_value.innerText) != -1) { select_value.value = select_value.value.replace(td_value.innerText, ''); } } } function bb() { var obj = document.getElementById("ds"); if (obj.style.display == "") { obj.style.display = "block"; } else if (obj.style.display == "none") { obj.style.display = "block"; } else if (obj.style.display == "block") { obj.style.display = "none"; } } function inDaohang(divname, obj) { var f = false; while (obj.parentNode) { if (obj.name == divname) { return true; } obj = obj.parentNode; } return false; } function closeDaohang(e, divname, aname) { if (e.id != aname && e.id != 'where' && e.id.indexOf("td") == -1 && e.id.indexOf("check") == -1) if (!inDaohang(divname, e)) { var a = document.getElementsByName(divname); for (var i = 0; i < a.length; i++) { a[i].style.display = 'none'; } } } .c1 { background-Color: #dddddd; /* bgColor:#dddddd; */ } .c0 { background-Color: #ffffff; /* bgColor:#dddddd; */ } body { margin: 0px; SCROLLBAR-FACE-COLOR: #e0edfd; SCROLLBAR-HIGHLIGHT-COLOR: #dfe8f4; SCROLLBAR-SHADOW-COLOR: #2c7cda; SCROLLBAR-3DLIGHT-COLOR: #2c7cda; SCROLLBAR-ARROW-COLOR: #14549f; SCROLLBAR-TRACK-COLOR: #eaf5fd; SCROLLBAR-DARKSHADOW-COLOR: #ffffff; SCROLLBAR-BASE-COLOR: #e0edfd; } .menu { display: none; } input.blur { border: 1px solid #99BBE8; background: #FFFFFF; height: 18px; } .tableborder { border: solid 1px #CCCCCC; border-collapse: collapse; font-size: 12px; }
第五种:
Document * { box-sizing: border-box; } .hint-input-span-container { width: 100%; background-color: #fff; border: 1px solid #ccc; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); display: inline-block; padding: 2px 4px; color: #555; vertical-align: middle; border-radius: 1px; max-width: 100%; line-height: 30px; } .hint-input-span-container .tag { padding: -2px; font-size: 12px; font-family: serif; ; margin-right: 2px; margin-top: 2px; margin-bottom: 2px; display: inline-block; } .label { font-size: 10px; padding: 4px 6px; border: none; text-shadow: none; border-radius: 3px; font-weight: 200; } .label-primary { background: #2693FF; color: white; } .hint-input-span-container span i[data-role='remove'] { cursor: pointer; } .tag { margin-right: 2px; color: white; } .tag [data-role="remove"] { margin-left: 2px; cursor: pointer; } input[name='hint-search'] { border: none; box-shadow: none; outline: none; background-color: transparent; padding: 0; margin: 0; width: 100%; max-width: inherit; } .hint-block { position: absolute; width: 100px; max-height: 120px; background-color: #fff; overflow: auto; display: none; z-index: 9999; } .hint-ul { text-decoration: none; list-style-type: none; padding-left: 5px; } .hint-ul li { font-size: 14px; padding: 2px 4px; } .hint-ul li:hover { background-color: #eee; } $(function () { //json数据包 var data = { data: ["123", "北京你好", "北京欢迎您", "北京好", "海洋", "海洋广利局", "我海洋", "我吃惊", "我啦啦啦啦", "我不能忍", "机构", "日本", "俄罗斯的山", "埃塞俄比亚", "伊巴卡", "比比比"] }; //获取后面需要多次调用的dom对象 var $hintSearch = $("input[name='hint-search']"); var $hintSearchContainer = $(".hint-input-span-container"); var $hintBlock = $(".hint-block"); var $hintUl = $(".hint-ul"); //初次调用添加词典 addDictionary(data.data, addUlListener); //设置词典列表宽度 setHintSearchContainerWidth(); //实现响应式 监听resize事件 $(window).bind('resize', setHintSearchContainerWidth); //获得焦点 $hintSearch.focus(function () { animteDown(); }); //失去焦点 //设置延迟为了可以监听到click的响应 $hintSearch.blur(function () { setTimeout(function () { animateUp(); }, 200); }); //TAB 与 enter事件 //监听tab与enter两个键位 如果input内有输入的内容,则添加span //注意最后要阻止一下事件冒泡 防止跳转与切换焦点 $hintSearch.keydown(function (e) { switch (e.which) { case 9: case 13: { var text = $hintSearch.val(); if (!$.trim(text)) { $hintSearch.val(""); e.preventDefault(); return; } if (!checkContainerHas(text)) { $hintSearch.before('' + text + ' '); addSpanListenr(); } //console.log($hintSearch.val()); $hintSearch.val(""); $hintSearch.focus(); e.preventDefault(); break; } default: ; } }); //检测输入配对 //对输入内容在li中进行匹配 如果包含字符串可以找到并返回 //搜索方法可以自行修改,只要保证返回一个搜索后的数组即可 $hintSearch.keyup(function (e) { var text = $hintSearch.val(); if (!$.trim(text)) { updateDictionary(data.data, addUlListener); } var tmparr = data.data.filter(function (x) { return x.indexOf(text) != -1; }) if (tmparr.length === 0) { tmparr.push("无匹配条目"); } updateDictionary(tmparr, addUlListener); }) //函数库 //添加用户常用字典库 function addDictionary(dataarr, callback) { for (var i = 0; i < dataarr.length; i++) { $hintUl.append('' + dataarr[i] + ''); } callback(); } //更新搜索内容 function updateDictionary(dataarr, callback) { $hintUl.empty(); addDictionary(dataarr, callback); } //向下滑动动画 //封装改变样式边框 function animteDown() { $hintBlock.slideDown('fast').css({ 'border': '1px solid #96C8DA', 'border-top': '0px', 'box-shadow': '0 2px 3px 0 rgba(34,36,38,.15)' }); $hintSearchContainer.css({ 'border': '1px solid #96C8DA', 'border-bottom': '0px', 'box-shadow': '0 2px 3px 0 rgba(34,36,38,.15)' }); } //向上滑动动画 function animateUp() { $hintBlock.slideUp('fast', function () { $hintSearchContainer.css({ 'border': '1px solid #ccc' }); }); } //检验是否与输入的重复 function checkContainerHas(text) { var flag = 0; $(".hint-input-span-container span").each(function () { if ($.trim(text) == $.trim($(this).text())) { flag = 1; return; } }); return flag ? true : false; } //设置hint-input-span-container宽度 function setHintSearchContainerWidth() { var hint_width = $hintSearchContainer.width() + 2 * parseInt($hintSearchContainer.css('padding-left').match(/[0-9]+/)[0]) + 2 * parseInt($hintSearchContainer.css('border-left').match(/[0-9]+/)[0]); $hintBlock.css({ 'width': hint_width }); } //绑定click事件 function addUlListener() { $hintUl.delegate('li', 'click', function () { var text = $(this).text(); if (!checkContainerHas(text)) { $hintSearch.before('' + text + ' '); addSpanListenr(); } $hintSearch.val(""); animateUp(); }) } //监听 span事件 function addSpanListenr() { $(".hint-input-span-container span").delegate("i", 'click', function () { $(this).parent().remove(); }) } })