JS文本框下拉多选值的方法
第一种:<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JS复选框向一个文本框中传值的多选效果</title><style type="text/css">i
·
第一种:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS复选框向一个文本框中传值的多选效果</title>
<style type="text/css">
input {
margin-right: 3px
}
label {
margin: 0 5px
}
</style>
<script type="text/javascript">
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(",");
}
}
}
</script>
</head>
<body>
<p><input type="text" id="tt" readonly /></p>
<div id="box">
<label><input type="checkbox" value="a" />a</label>
<label><input type="checkbox" value="b" />b</label>
<label><input type="checkbox" value="c" />c</label>
<label><input type="checkbox" value="d" />d</label>
<label><input type="checkbox" value="e" />e</label>
<label><input type="checkbox" value="f" />f</label>
</div>
</body>
</html>
第二种:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>原生js实现多选功能</title>
</head>
<body>
<div>
<label>多选功能:</label>
<select id="multipleSelect">
<option selected="selected" disabled="disabled" style='display: none' value=''></option>
<option>HTML</option>
<option>CSS</option>
<option>Javascript</option>
<option>vue</option>
<option>react</option>
</select>
</div>
<script>
/*基本思路:
1、创建一个隐藏的option,添加到select的最后;
2、每次选中的值都存入这个option,如果已经选中,当再次选择时,就会删掉;
3、若已选择了值,就将隐藏的option的selected属性设置为true,以便获取多选内容
*/
let values = []; //存储选择的内容
let opts = []; //存储option标签
let select = document.getElementById("multipleSelect");
for(let i=0;i<select.length;i++){
opts.push(select.item(i));
}
//创建一个隐藏起来的option
let optionHide = document.createElement('option');
optionHide.hidden=true;
select.appendChild(optionHide);
select.addEventListener('input',function (){
let value = this.options[this.selectedIndex].value; //获取当前选择的值
this.options[this.selectedIndex].style="background: pink"; //选中的option背景为粉色
let index = values.indexOf(value); //判断是否被选择,返回-1说明没选择,否则已被选择
if(index>-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);// 打印多选的内容
});
</script>
</body>
</html>
第三种:
摘自文章:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
(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 += '<option value="' + data[i].value + '">' + data[i].text + '</option>'
}
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', '<i style="color: red;font-size: 12px">*可多选</i>');
}
}
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;
}
}
})();
</script>
<title>文本框下拉单选多选</title>
</head>
<body>
<select multip="m" style="width: 180px;height:30px;margin-left: 200px">
<option>---请选择---</option>
<option value="1">桃子</option>
<option value="2">大苹果</option>
<option value="3">樱桃</option>
<option value="4">草莓</option>
</select>
<select imultip id="n" style="width: 180px;height:30px;margin-left: 200px">
<option>---请选择---</option>
<option value="1">板凳</option>
<option value="2">椅子</option>
<option value="3">桌子</option>
<option value="4">书架</option>
</select>
<script>
selectMultip.register();
</script>
</body>
</html>
第四种:
<html>
<head>
<title>下拉框中的复选框</title>
</head>
<script>
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';
}
}
}
</script>
<style type="text/css">
.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;
}
</style>
<body onclick="closeDaohang(event.srcElement||event.target,'ds','xx')">
<form>
<div id="xx">
<table>
<tr>
<td>
<input type="text" id="where" name="where" style="width:100px" onclick="bb()"
onblur="this.className='blur'" onfocus="this.className='focus'" class="blur" readonly>
</td>
</table>
</div>
<div id="ds" style="display:none;padding:0px 0px 0px 0px; margin:0;">
<table border="0" cellpadding="0" cellspacing="0" class="tableborder">
<tr>
<td id="td1"><input type="Checkbox" id="check1" name="idol02" value="1" onclick="aa(this,'td1')">你是1
</td>
<td id="td4"><input type="Checkbox" id="check4" name="idol02" value="4" onclick="aa(this,'td4')">你是4
</td>
</tr>
<tr>
<td id="td2"><input type="Checkbox" id="check2" name="idol02" value="2" onclick="aa(this,'td2')">你是2
</td>
<td id="td5"><input type="Checkbox" id="check5" name="idol02" value="5" onclick="aa(this,'td5')">你是5
</td>
</tr>
<tr>
<td id="td3"><input type="Checkbox" id="check3" name="idol02" value="3" onclick="aa(this,'td3')">你是3
</td>
<td id="td6"><input type="Checkbox" id="check6" name="idol02" value="6" onclick="aa(this,'td6')">你是6
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
第五种:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-2.1.0.min.js"></script>
<style>
* {
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;
}
</style>
</head>
<body>
<!-- 最外层div 可以任意指定 主要用于定义子元素宽度 -->
<div class="col-xs-10" style="width:800px">
<!-- 表单label 添加文字提示 -->
<label for="" class="label-control">全文检索</label>
<!-- 多选承接div 以后会动态添加span -->
<div class="hint-input-span-container">
<!-- 表单元素 用来绑定监听事件以及接收用户输入 该层上方会动态添加span -->
<input type="text" name="hint-search" value="" placeholder="选定关键字或按下tab或按下enter来分割关键字">
</div>
<!-- 包含下拉列表列 -->
<div class="hint-block">
<!-- 根据json数据包动态添加li -->
<ul class="hint-ul">
</ul>
</div>
</div>
</body>
<script>
$(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('<span class="tag label label-primary">' + text + ' <i class="fa fa-times" data-role="remove"></i><i> </i></span>');
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('<li>' + dataarr[i] + '</li>');
}
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('<span class="tag label label-primary">' + text + ' <i class="fa fa-times" data-role="remove"></i><i> </i></span>');
addSpanListenr();
}
$hintSearch.val("");
animateUp();
})
}
//监听 span事件
function addSpanListenr() {
$(".hint-input-span-container span").delegate("i", 'click', function () {
$(this).parent().remove();
})
}
})
</script>
</html>
更多推荐
已为社区贡献7条内容
所有评论(0)