0

I need to have updated values when i click the button, but it doesn't work. I'm getting only empty array.

var title = form.title.value;
var data = form.date.value;
var priority = form.priority.value;
var description = form.textarea.value;
var check = form.check.value;

document.querySelector("button").addEventListener('click', function() {
    var obj = {};
    var arr = [];
    obj.title = title;
    obj.date = data;
    obj.priority = priority;
    obj.description = description;
    obj.check = check;
    arr.push(obj);
    localStorage.setItem('todo_list', JSON.stringify(arr));
    var tasks = JSON.parse( localStorage.getItem('todo_list') );
    console.log(tasks);
});
1
  • The vars set outside the click handler are set immediately, and not updated, so no matter what's on the form when the button is clicked, the values used are probably blank from when the JS first loaded. Commented Nov 28, 2017 at 18:24

1 Answer 1

1

You're fetching all the form values when your code first runs, presumably when the page is loaded. Shouldn't you be fetching them after the button is clicked? Remove all five of the var statements at the top, and fetch the form values directly inside the click event listener:

document.querySelector("button").addEventListener('click', function() {
    var obj = {};
    var arr = [];
    obj.title = form.title.value;
    obj.date = form.date.value;
    obj.priority = form.priority.value;
    obj.description = form.textarea.value;
    obj.check = form.check.value;
    arr.push(obj);
    localStorage.setItem('todo_list', JSON.stringify(arr));
    var tasks = JSON.parse( localStorage.getItem('todo_list') );
    console.log(tasks);
});

You can also clean up the code a bit by setting all the values inside the object/array literals. Depending on what you need, this can be a nicer way to do it:

document.querySelector("button").addEventListener('click', function() {
    var arr = [
        {
            title: form.title.value,
            date: form.date.value,
            priority: form.priority.value,
            description: form.textarea.value,
            check: form.check.value
        }
    ];
    localStorage.setItem('todo_list', JSON.stringify(arr));
    var tasks = JSON.parse( localStorage.getItem('todo_list') );
    console.log(tasks);
});
Sign up to request clarification or add additional context in comments.

Comments

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.