[英]Getting Value of Multiple Selected Checkbox with Same Name in JavaScript
I can't seem to get the correct output. I am not sure if my for loop is the problem.我似乎无法获得正确的 output。我不确定我的 for 循环是否有问题。 Please excuse my variable names.请原谅我的变量名。 I know I know, I made them very obvious.我知道我知道,我让他们很明显。 :) By the way, should I use var here or let is fine? :) 顺便问一下,我应该在这里使用 var 还是 let 好?
I have read somewhere that when declaring a variable:我在某处读到声明变量时:
var => function-scoped var => 函数范围
ES6 (ES2015): let, const => block-scoped ES6 (ES2015): let, const => 块作用域
The check all button won't work as well.选中所有按钮也不会起作用。
Your input will be highly appreciated.非常感谢您的意见。
<html>
<head>
<title>Get Checkbox Value</title>
<style type="text/css">
body {
padding-top: 10px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
background-color: #ede5e5;
height: 100vh;
}
div {
width: 50%;
margin: auto;
border: 1px solid lightgray;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%);
box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%);
padding: 10px;
padding-left: 20px;
padding-bottom: 30px;
background-color: white;
}
button {
padding:5px;
font-size: 16px;
font-weight: bold;
}
label {
font-size: 18px;
font-weight: bold;
}
input [type=checkbox] {
width: 20px;
height: 20px;
}
</style>
</head>
<body>
<div style="">
<h2>Select a Programming Language You Love</h2>
<form id="frm-lang">
<input type="checkbox" name="languages" value="JavaScript">
<label>JavaScript</label><br/>
<input type="checkbox" name="languages" value="PHP">
<label>PHP</label><br/>
<input type="checkbox" name="languages" value="Pyton">
<label>Pyton</label><br/>
<input type="checkbox" name="languages" value="C#">
<label>C#</label><br/>
<input type="checkbox" name="languages" value="C++">
<label>C++</label><br/><br/>
<button id="btnSubmit">Submit</button>
<button id="btnCheckAll">Check All</button>
</form>
</div>
<script>
let formvar = document.getElementById('frm-lang');
let valuesvar = [];
formvar.addEventListener('submit', function(e) {
e.preventDefault ();
let checkboxesvar = document.getElementsByName('languages');
for (let i = 0; i < checkboxesvar.length; i++) {
if (checkboxesvar[i].checked == true) {
valuesvar.push(checkboxesvar[i].value);
}
}
alert('The values(s): ' + valuesvar.toString());
});
// for the check all button
document.getElementById('btnCheckAll').onclick = function(e) {
e.preventDefault();
let checkboxesvar = document.getElementsByName('languages');
for (let i=0; i < checkboxesvar.length; i++) {
checkbboxesvar[i].checked = true;
}
}
</script>
</body>
</html>
In your submit
listener, you are not clearing your array, so it will keep the values from the previous submission, you need to clear it, so move it to inside the listener在您的submit
侦听器中,您没有清除您的数组,因此它将保留上一次提交的值,您需要清除它,因此将其移至侦听器内部
in your checkAll
you had a typo, checbboxesvar
with 2 b
在您的checkAll
中,您有一个错字,带有 2 b
的checbboxesvar
I improved your code a bit, renamed variable names and left one line solutions.我稍微改进了您的代码,重命名了变量名并留下了一行解决方案。
const form = document.getElementById('frm-lang'); const checkboxes = document.getElementsByName('languages'); const checkAll = document.getElementById('btnCheckAll'); const clearAll = document.getElementById('btnClearAll'); form.addEventListener('submit', e => { e.preventDefault(); let values = []; // for loop solution //for (let i = 0; i < checkboxes.length; i++) { // if (checkboxes[i].checked) { // values.push(checkboxes[i].value); // } //} //one liner solution checkboxes.forEach(el => el.checked && values.push(el.value)) console.log('The values(s): ' + values); }); // for the check all button checkAll.addEventListener('click', () => { // for loop solution //for (let i = 0; i < checkboxes.length; i++) { // checkboxes[i].checked = true; //} //one liner solution checkboxes.forEach(el => el.checked = true) }) clearAll.addEventListener('click', () => { // for loop solution //for (let i = 0; i < checkboxes.length; i++) { // checkboxes[i].checked = false; //} //one liner solution checkboxes.forEach(el => el.checked = false) })
body { padding-top: 10px; font-family: Verdana, Geneva, Tahoma, sans-serif; background-color: #ede5e5; height: 100vh; } .container { width: 50%; margin: auto; border: 1px solid lightgray; border-radius: 5px; box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%); padding: 10px 10px 30px 20px; background-color: white; } button { padding: 5px; font-size: 16px; font-weight: bold; } label { font-size: 18px; font-weight: bold; } input[type=checkbox] { width: 20px; height: 20px; }
<div class="container"> <h2>Select a Programming Language You Love</h2> <form id="frm-lang"> <input type="checkbox" name="languages" value="JavaScript"> <label>JavaScript</label><br/> <input type="checkbox" name="languages" value="PHP"> <label>PHP</label><br/> <input type="checkbox" name="languages" value="Pyton"> <label>Pyton</label><br/> <input type="checkbox" name="languages" value="C#"> <label>C#</label><br/> <input type="checkbox" name="languages" value="C++"> <label>C++</label><br/><br/> <button id="btnSubmit">Submit</button> <button type="button" id="btnCheckAll">Check All</button> <button type="button" id="btnClearAll">Clear All</button> </form> </div>
你拼错了 checkboxesvar 你的变量是 checkboxesvar
Any <button>
that's nested within a <form>
is type="submit"
by default, so add type="button"
to the "Check All" button and you don't need anything on a <button>
if it triggers a submit event.默认情况下,嵌套在<form>
中的任何<button>
都是type="submit"
,因此将type="button"
添加到“Check All”按钮,如果<button>
触发了提交事件。
The example uses the HTMLFormElement and HTMLFormControlsCollection interfaces to reference all Form Controls .该示例使用HTMLFormElement和HTMLFormControlsCollection接口来引用所有表单控件。 Also, the "Check All" button toggles all checkboxes checked/unchecked.此外,“全选”按钮可切换选中/未选中的所有复选框。
Details are commented in example细节在例子中注释
.as-console-row::after { width: 0; font-size: 0; } .as-console-row-code { width: 100%; word-break: break-word; } .as-console-wrapper { max-height: 60% !important; max-width: 25%; }
<html> <head> <title>Get Checkbox Value</title> <style> html { font: 900 2.5ch/1.2 Veranda; } body { padding-top: 10px; height: 100vh; } fieldset { width: 50%; margin: auto; border: 1px solid lightgray; border-radius: 5px; box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%); padding: 10px; padding-left: 20px; padding-bottom: 30px; background-color: white; } menu { display: flex; justify-content: flex-end; align-items: center; margin: 0; list-style: none; } button { padding: 3px 5px; font: inherit; cursor: pointer; } input [type=checkbox] { width: 20px; height: 20px; } </style> </head> <body> <form id="lang"> <fieldset> <legend> <h2>Favorite Language</h2> </legend> <input type="checkbox" name="languages" value="JavaScript"> <label>JavaScript</label><br/> <input type="checkbox" name="languages" value="PHP"> <label>PHP</label><br/> <input type="checkbox" name="languages" value="Python"> <label>Python</label><br/> <input type="checkbox" name="languages" value="C#"> <label>C#</label><br/> <input type="checkbox" name="languages" value="C++"> <label>C++</label><br/><br/> <menu> <button>Submit</button> <button id="all" type='button'>Check All</button> </menu> </fieldset> </form> <script> // Reference the form const form = document.forms.lang; // Reference all inputs, buttons, and fieldsets const IO = form.elements; // Collect all [name='languages'] into an array const chx = [...IO.languages]; /* Bind an event handler to the submit event When <form> is submitted instead of the default behavior the values of all checkboxes will be collected into an array then logged on console */ let values; form.onsubmit = collectValues; function collectValues(e) { e.preventDefault(); values = chx.map(c => c.value); console.log(values); } /* Bind button#all to the click event Invoke toggleCB(e) when clicked */ IO.all.onclick = toggleCB; function toggleCB(e) { // Toggle the ".check" class on button this.classList.toggle('check'); /* If the button has ".check" class... ...check all checkboxes... ...otherwise uncheck all checkboxes */ if (this.classList.contains('check')) { chx.forEach(c => c.checked = true); } else { chx.forEach(c => c.checked = false); } } </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.