0

I am taking the CS50 web programming course.

I try to do it as the same way, however it doesn't work.

I wonder what's wrong with the code.

Why does not it work after I add the "DOMContentLoaded"?

<!DOCTYPE html>
<html>
    <head>
        <script>
            document.addEventListener("DOMContentLoaded", function(){

                document.querySelector('#submit').disabled = true;

                document.querySelector('#task').onkeyup = () =>{
                    //task's input has keyup which represents "not null"
                    document.querySelector('#submit').disabled = false;
                };

                document.querySelector('#new-task').onsubmit = () =>{
                    
                    //creates new item for list
                    const li = document.createElement('li');
                    li.innerHTML = document.querySelector('#task').value;
                
                    //Add new item to task list
                    document.querySelector('#tasks').append(li);

                    //Clear input li
                    document.querySelector('#task').value = '';

                    document.querySelector('#submit').disabled = true;

                    return false;
                };
                
            });
        </script>
        <title>List tasks</title>
    </head>
    <body>
        <h1>Task</h1>
        <ul id="tasks"></ul>
        <form id="new-task">
            <input id="task" autocomplete="off" autofocus placeholder="New Task" type="text">
            <input type="submit">
        </form>
    </body>
</html>
Leo Hsu
  • 19
  • 4

1 Answers1

1

The submit input is missing an id of "submit" you are trying to query against. It's returning null/undefined which is why you get an error trying to set disabled value. Add an id to the submit input:

    <body>
        <h1>Task</h1>
        <ul id="tasks"></ul>
        <form id="new-task">
            <input id="task" autocomplete="off" autofocus placeholder="New Task" type="text">
            <input id="submit" type="submit">
        </form>
    </body>
Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91