gpt4 book ai didi

javascript - 使用 JavaScript 显示选定的复选框值

转载 作者:行者123 更新时间:2023-12-03 11:10:03 26 4
gpt4 key购买 nike

我一直在尝试创建复选框并显示它们的值。当您尝试仅选择其中之一时,它会起作用。当您尝试选择多个时,它仅显示所选的最高值。我只想用javascript而不是jquery来做到这一点。如何显示所有选定复选框的所有值?

这是到目前为止的代码:

HTML:

<!doctype html>
<html>
<head>
<title>Javascript checkboxes in real time</title>
<link rel = "stylesheet" href = "css/default.css">
</head>
<body>
<form action = "" method = "post">
<input type="checkbox" id = "1" value = "1">1<br>
<input type="checkbox" id = "2" value = "2">2<br>
<input type="checkbox" id = "3" value = "3">3<br>
<input type="checkbox" id = "4" value = "4">4<br>
<input type="checkbox" id = "5" value = "5">5<br>
</form>
<section></section>
<script src = "js/default.js"></script>
</body>
</html>

Javascript:

var checkbox = document.getElementsByTagName('input');
var section = document.getElementsByTagName('section');

setInterval(function(){
for(var i = 0; i <= checkbox.length - 1; i++){
if(checkbox[i].checked){
section[0].innerHTML = checkbox[i].value;
break;
}
else{
section[0].innerHTML = null;
}
}
}, 10);

最佳答案

你的代码有几个问题,你无休止地每 10 毫秒查询 DOM 一次,没有什么充分的理由。 DOM 元素在发生事情时会触发事件。

var section = document.getElementsByTagName('section')[0];
var inputs = document.getElementsByTagName('input');

// Document was changed!
document.addEventListener('change', function(event) {
// Specifically, an input was changed in the document!
if (event.target.tagName === 'INPUT') {
// Update the section
updateCheckboxStatus(section);
}
});

// This function updates an element with the input status
function updateCheckboxStatus(element) {
// Clear the element first
element.textContent = '';
// Loop through each of the inputs
[].forEach.call(inputs, function(input) {
// If checked, add to the element
if (input.checked) { element.textContent += input.value + " "; }
});
}
<form action="" method="post">
<input type="checkbox" id="1" value="1">1
<br>
<input type="checkbox" id="2" value="2">2
<br>
<input type="checkbox" id="3" value="3">3
<br>
<input type="checkbox" id="4" value="4">4
<br>
<input type="checkbox" id="5" value="5">5
<br>
</form>
<section></section>

关于javascript - 使用 JavaScript 显示选定的复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27638074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com