Reputation: 5131
I am creating a todo app. It consists of 3 task to do with status set to false
by default. The fields are populated using Javascript.
When the radio button is checked, it should run the completeTask()
function. But it is giving me the undefined function error. Please Help!
let todoApp = (() => {
const container = document.getElementById('todoLister');
const todoList = [
{
task: 'Get Up',
status: false
},
{
task: 'Eat stuff',
status: false
},
{
task: 'Goto College',
status: false
}
];
todoList.forEach((el, id) => {
const label = document.createElement('label');
const radio = document.createElement('input');
const br = document.createElement('br');
if(el.status)
label.innerText = el.task+'- Done Successfully';
else
label.innerText = el.task+'- Not Done';
label.setAttribute('for', el.task);
radio.value = id;
radio.setAttribute('type', 'radio');
radio.setAttribute('onchange', 'completeTask('+id+')');
container.appendChild(radio);
container.appendChild(label);
container.appendChild(br);
});
let completeTask = (id) => {
todoList[id].status = true;
if(todoList[id].status)
document.getElementsByTagName('label')[id].innerText = 'Done Successfully';
}
})();
<div id="todoLister">
</div>
Upvotes: 0
Views: 29
Reputation: 28475
With your function inside the todoApp
, it was not available globally. You need to move your function and data outside the function so as it is visible globally.
const todoList = [{
task: 'Get Up',
status: false
},
{
task: 'Eat stuff',
status: false
},
{
task: 'Goto College',
status: false
}
];
let completeTask = (id) => {
todoList[id].status = true;
if (todoList[id].status)
document.getElementsByTagName('label')[id].innerText = 'Done Successfully';
}
let todoApp = (() => {
const container = document.getElementById('todoLister');
todoList.forEach((el, id) => {
const label = document.createElement('label');
const radio = document.createElement('input');
const br = document.createElement('br');
if (el.status)
label.innerText = el.task + '- Done Successfully';
else
label.innerText = el.task + '- Not Done';
label.setAttribute('for', el.task);
radio.value = id;
radio.setAttribute('type', 'radio');
radio.setAttribute('onchange', 'completeTask(' + id + ')');
container.appendChild(radio);
container.appendChild(label);
container.appendChild(br);
});
})();
<div id="todoLister">
</div>
Upvotes: 1