I would like to add and remove elements from an array when a user clicks on a checkbox. This is then printed to an HTML document. I have completed this before by emptying the array each time function runs however I'd prefer to remove the item rather than empty the array and add the checked items.
https://jsfiddle.net/Buleria28/zz0x6hgc/
/*Object that includes array*/
information {
letters[]
}
/*Function*/
function letter() {
var checkbox = Array.from(document.getElementsByName("test")); //creates array from checkboxes
for (var i = 0; i < checkbox.length; i++) {
if (checkbox.checked) {
information.letters.push(checkbox[i].value);
} else {
var sbVal = checkbox[i].value;
if (information.letters.includes(sbVal) == true) {
var j = indexOf(sbVal);
information.letters.splice(j, 1);
}
}
}
var showAbc = information.letters.join(", "); //converts to string
document.getElementById("displaylet").innerHTML = showAbc; //prints to HTML document
}
/*Event Listener*/
var box = document.getElementsByName("test");
if (box[0].addEventListener) {
for (var i = 0; i < box.length; i++) {
box[i].addEventListener("change", letter, false);
}
} else if (box[0].attachEvent) {
for (var i = 0; i < box.length; i++) {
box[i].attachEvent("onchange", letter);
}
}
The HTML is here:
<div>
<label><input type="checkbox" name="test" value="A">A</label>
<label><input type="checkbox" name="test" value="B">B</label>
<label><input type="checkbox" name="test" value="C">C</label>
<label><input type="checkbox" name="test" value="D">D</label>
</div>
<p id="displaylet"></p>