Reputation: 61
Ok, so I'm learning Javascript and for my first small project I want to make a task organizer. When I click the button the first time to add a task it adds it to the page, and then when I click the button to add another task it throws a type error. Do I need some kind of loop to catch the error or is the problem calling the function when the button is clicked?
Error
ToDo.html:12 Uncaught TypeError: getTask is not a function
at HTMLButtonElement.onclick (ToDo.html:12)
HTML
<body>
<div class='container'>
<p>Task Tracker</p>
<input type="text" name="Title" id="taskInput">
<button onclick="getTask()"> Add Task </button>
<div class="todo" id="showTask">
</div>
</div>
</body>
Javasript
var getTask;
var task;
function getTask(){
getTask = document.getElementById("taskInput").value;
task = getTask;
console.log(task);
document.getElementById('showTask').innerHTML = task;
}
Upvotes: 1
Views: 5640
Reputation: 3017
getTask is declared as a Function not a global variable
// getTask is a function not declare as global variable
var task;
function getTask(){
task = document.getElementById("taskInput").value;;
console.log(task);
document.getElementById('showTask').innerHTML = task;
}
<div class='container'>
<p>Task Tracker</p>
<input type="text" name="Title" id="taskInput">
<button onclick="getTask()"> Add Task </button>
<div class="todo" id="showTask">
</div>
</div>
Upvotes: 1
Reputation: 522
As you wrote into the comment you named the variable the same way that you named your function. You actually don't need to initialise the variable outside of the function. For your second question in the comment, your variable becomes the new task because you actually do replace the whole content of the variable. You need to use an array instead.
var task = [];
function getTask(){
var getTask = document.getElementById("taskInput").value;
task.push(getTask);
console.log(task);
document.getElementById('showTask').innerHTML = task;
}
See the first line var task = [];
and the fourth line task.push(getTask);
.
Upvotes: 1