I am trying to get all checked checkboxes and create li elements with them. I want the li elements to show up as soon as the checkboxes are checked. And can I do that without using value attribute in input? I already looked up there is a way to do that with value but that doesn't work with my code.
I have this code
const checkboxes = document.getElementsByTagName('input').type == 'checkbox';
function getChecked() {
let checked = [];
for (let i = 0; i < checkboxes.length; i++) {
let checkbox = checkboxes[i];
if (checkbox.checked) {
const rightBox = document.getElementsByClassName('main-container-2')[0];
const newDiv = document.createElement('div');
rightBox.appendChild(newDiv);
const ul = document.createElement('ul');
newDiv.appendChild(ul);
const li = document.createElement('li');
ul.appendChild(li);
const label = document.createElement('label');
li.innerHTML = label.innerHTML;
}
}
return checked;
};
getChecked();
<div class="article-main">
<div class="article-left">
<div>
<input type="checkbox" id="checkbox1">
<label for="checkbox1">Onion</label>
</div>
<div>
<input type="checkbox" id="checkbox2">
<label for="checkbox2">Spring Onion</label>
</div>
<div>
<input type="checkbox" id="checkbox3">
<label for="checkbox3">Egg</label>
</div>
</div>
</div>
I give you an example for your reference:
document.addEventListener("DOMContentLoaded", function(event) {
const checkBoxes = document.querySelectorAll("input[type=checkbox]");
for (let i = 0; i < checkBoxes.length; i++) {
let checkBox = checkBoxes[i];
checkBox.addEventListener("click", e => {
if (e.target.checked) {
const rightBox = document.getElementsByClassName('main-container-2')[0];
const newDiv = document.createElement('div');
rightBox.appendChild(newDiv);
const ul = document.createElement('ul');
newDiv.appendChild(ul);
const li = document.createElement('li');
ul.appendChild(li);
let l=e.target.nextElementSibling;
li.innerHTML = l.innerHTML;
}
});
}
});
<div class="article-main">
<div class="article-left">
<div>
<input type="checkbox" id="checkbox1">
<label for="checkbox1">Onion</label>
</div>
<div>
<input type="checkbox" id="checkbox2">
<label for="checkbox2">Spring Onion</label>
</div>
<div>
<input type="checkbox" id="checkbox3">
<label for="checkbox3">Egg</label>
</div>
</div>
</div>
<div class="main-container-2">
</div>