I can't seem to get the correct output. I am not sure if my for loop is the problem. 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?
I have read somewhere that when declaring a variable:
var => function-scoped
ES6 (ES2015): let, const => block-scoped
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>