我创建了一个多选ui组件,我必须将所选值推送到数组并在按钮值中显示相同的值。我在警告框中获取所选值但无法在按钮中获取。
单击复选框后,请帮我将所选项目值显示为按钮值。
段:
function getCheckedCheckboxesFor(checkboxName) {
var checkboxes = document.querySelectorAll('input[name="' + checkboxName + '"]:checked'),
values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
return values;
}

.check-multiple {
display: inline-block;
height: 60px;
overflow-y: scroll;
border: 1px solid gray;
}
.check-multiple input {
float: left;
}
.check-multiple label {
display: inline-block;
}
.check-multiple span {
display: inline-block;
width: 100%;
}
.check-multiple input:checked~span {
background: #03f;
color: white;
}

<div class="check-multiple">
<label for="veh"><input value="car" type="checkbox" name="veh"><span>car</span></label>
<label for="veh"><input value="scooter" type="checkbox" name="veh"><span>scooter</span></label>
<label for="veh"><input value="bus" type="checkbox" name="veh"><span>bus</span></label>
</div>
<input type="button" onclick="alert(getCheckedCheckboxesFor('veh'));" value="Get Values" />
&#13;
答案 0 :(得分:2)
你的问题有点奇怪,这是你想要完成的事情吗?
编辑:使用onchange事件触发复选框上按钮文本的更改值
function getCheckedCheckboxesFor(checkboxName) {
}
function myFunction(val) {
var checkboxes = document.querySelectorAll('input[name="' + val + '"]:checked'),
values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
document.getElementById("demo").value = values;
}
&#13;
.check-multiple {
display: inline-block;
height: 60px;
overflow-y: scroll;
border: 1px solid gray;
}
.check-multiple input {
float: left;
}
.check-multiple label {
display: inline-block;
}
.check-multiple span {
display: inline-block;
width: 100%;
}
.check-multiple input:checked~span {
background: #03f;
color: white;
}
&#13;
<div class="check-multiple">
<label for="veh"><input value="car" type="checkbox" name="veh" onchange="myFunction('veh')"><span>car</span></label>
<label for="veh"><input value="scooter" type="checkbox" name="veh" onchange="myFunction('veh')"><span>scooter</span></label>
<label for="veh"><input value="bus" type="checkbox" name="veh" onchange="myFunction('veh')"><span>bus</span></label>
</div>
<input type="button" onclick="alert(getCheckedCheckboxesFor('veh'));" value="Get Values" id="demo" />
&#13;