0

My instructor tasked us to build a 2D array and populate it with values from our HTML form. He gave us this example to create the array.

var tasks = new Array();
var index = 0;

He then said to insert the values into the two columns using this code.

tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;

However, something about these two lines is causing the script to break, because when I comment them out the final line of my script returns a value to the correct div. When I uncomment these lines no value is returned. Is there something wrong in my syntax?

This is my complete js file:

var tasks = new Array();
var index = 0;


function addTask() {
    var tempdate = new Date();
    var temptask = document.getElementById("taskinfo").value;
    var td = document.getElementById("taskdate").value;
    tempdate = td + " 00:00";

    tasks[index]["Date"] = tempdate;
    tasks[index]["Task"] = temptask;

    index++

    tasks.sort(function (a, b) { return b.date - a.date });

    var tablecode = "<table class = 'tasktable'>" +
        "<tr>"+
        "<th>Date</th>"+
        "<th>Task</th>"+
        "</tr>";
    for (var i = 0; i < tasks.length; i++) {
        tablecode = tablecode + "<tr>" +
            "<td>" + tasks[i]["Date"].toDateString() + " </td>" +
            "<td>" + tasks[i]["Task"] + " </td>" +
            "</tr>";
    }

    tablecode = tablecode + "</table>";
//I am only returning "temptask" to test with, I will be returning     "tablecode". 
    document.getElementById("bottomright").innerHTML = temptask;

return false;

}
1
  • Have you looked at your browser's JavaScript console (F12, in most browsers), it seems likely there's a reported error there that you're overlooking. Commented Dec 5, 2015 at 2:47

1 Answer 1

2

tasks[index] (in the first case, tasks[0]) doesn't yet exist, so you can't give it properties. Try this to create an object and assign it to tasks[index]:

tasks[index] = {
    Date: tempdate,
    Task: temptask
};

in place of

tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;

Alternatively, you can use

tasks[index] = {};
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help! If this or any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this, though. Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.