List Sorter
Sorts items by using a checkmark, then displays checked items when requested by button
by noingwhat
HTML
<body onload="myFunction()">
<div id="itemlist" style="display:none">
List Item 1
List item 2
List item 3
List item 4
List item 5
</div>
</body>
JavaScript
function checktags(tagnum){ // Check if each list item has the clicked tag checkmarked
var res = document.getElementById("itemlist").innerHTML.split(/\n/);
for (var i in res) {
var list = document.getElementById(i).getElementsByTagName("input");
var itemnum = + i + 1; var categorynum = + tagnum + 1; // only used for alert
if(list[tagnum].checked) alert("List item " + itemnum + ", checkbox " + categorynum + " has been selected");
else alert("List item " + itemnum + ", checkbox " + categorynum + " is UNchecked");
}
}
function myFunction() { // run on load
var res = document.getElementById("itemlist").innerHTML.split(/\n/); // get list items
res = res.filter(function(str) {return /\S/.test(str);}); // remove empty lines
var taglist = ["Tag 1", "Tag 2", "Tag 3", "Tag 4", "Tag 5"]
// pull each item from the initial hidden list, and give them each their own div
for (var i in taglist){
var buttonElement = document.createElement('button');
buttonElement.onclick = function() {checktags(i);}; // HERE LIES THE PROBLEM
var tagnum = + i + 1; // only used for alert
//alert("Creating button " + tagnum); // can uncomment for debugging
buttonElement.innerHTML = taglist[i];
document.body.appendChild(buttonElement);
}
// add 5 checkboxes to each div
for (var c in res) {
var newElement = document.createElement('div');
newElement.id = c;
newElement.innerHTML = + c + 1 + ") " + res[c]; // number the list
for( var j in taglist){
newElement.innerHTML += "<input type='checkbox' value='" + taglist[j] + "'>";
}
document.body.appendChild(newElement);
}
}