My program takes in user input of a string and checkbox and builds up a list to be displayed. (Check-list basically) Each list element consists of a string variable and a check-box input but I can't refer to a specific checkbox if say the third one would be ticked since the ID wouldn't be unique in this method. I feel as if there's a better approach. I'm new to stackoverflow so I apologize if the code is too much, little, confusing, etc.
Relevant Code (imo):
var taskArr= []; //String of tasks array
var compArr=[]; //comp = completed? task completion array, has bool
var isCompleted = 0;
document.getElementById('list').addEventListener('click',alternateValue);
function alternateValue(){
//Recheck all the actual clicked boxes and updates the array since the list members do not have a unique id. Another way?
alert("click works!");
var newChecks = document.getElementsByClass('');
//2nd alert, no alert.
alert(newChecks[0].checked);
compArr = [];
for(i = 0; i<newChecks.length;i++){
compArr.push(newChecks[i].checked);
}
}
function addTask(){
var check = document.getElementById('compInput').checked;
var task = document.getElementById('taskInput').value;
taskArr.push(task);
compArr.push(check);
alert(check);
//Check for correct value of.. the check
update();
}
function update(){
var tasks = '<ul>';
for(i =0; i< taskArr.length;i++){
if(compArr[i] == 0){
tasks = tasks.concat('<li>'+taskArr[i]+'<input type="checkbox" class="texts" placeholder="Done?"/></li>');
}
else{
tasks = tasks.concat('<li>'+taskArr[i]+'<input type="checkbox" class="texts" checked placeholder="Done?"/></li>');
}
}
tasks = tasks.concat('</ul>');
document.getElementById('list').innerHTML = tasks;
document.getElementById('comps').addEventListener('click',alternateValue);
}
Instead of referring the checkboxes with their
id's
you can refer to them using the class you are giving themclass="texts"
HTML:
Using only JavaScript: JavaScript demo
If you want a pure JavaScript solution then you need to create an event handler that handles the events on the checkboxes with
class="texts"
. Once the event is created you can use it by attaching a function to it and perform your required operations within the function.Using jQuery: jQuery demo
If you want to use jQuery you can write the below script instead of the above JavaScript.
Hope this helps!