Javascript TypeError, function is not a function

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;
}

Answer

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);.

Leave a Reply

Your email address will not be published. Required fields are marked *