Michael August
Michael August

Reputation: 29

what can make my form not to see my input value

I'm trying to get the task in my input, but its giving nothing when i console.log. this is the code.

const form = document.querySelector('#add-form');
const taskInput = document.querySelector('#task').value;
const addTask = document.querySelector('#add-task');
const list = document.querySelector('#list');

form.addEventListener('submit', (e) => {
    const li = document.createElement('li');

    li.innerHTML = taskInput;
    li.append(taskInput);
    list.appendChild(li);
    console.log(taskInput);
    e.preventDefault();
})

Upvotes: 1

Views: 37

Answers (2)

iKaio
iKaio

Reputation: 16

That way you are taking the value of the input before the user types something, do this:

const form = document.querySelector('#add-form');
const taskInput = document.querySelector('#task'); // remove the .value here
const addTask = document.querySelector('#add-task');
const list = document.querySelector('#list');

form.addEventListener('submit', (e) => {
    const li = document.createElement('li');

    li.innerHTML = taskInput.value; // and put here
    li.append(taskInput);
    list.appendChild(li);
    console.log(taskInput.value); // and here
    e.preventDefault();
})

Upvotes: 0

N. Brittain
N. Brittain

Reputation: 116

You are querying for the value at initialization of the script. Try retrieving the value on submit e.g.

const form = document.querySelector('#add-form');
const addTask = document.querySelector('#add-task');
const list = document.querySelector('#list');

form.addEventListener('submit', (e) => {
    const li = document.createElement('li');

    var taskInput = document.querySelector('#task').value;

    li.innerHTML = taskInput;
    li.append(taskInput);
    list.appendChild(li);
    console.log(taskInput);
    e.preventDefault();
})

Upvotes: 3

Related Questions