Search code examples
javascriptbuttonenteronkeypress

How to use enter to append my <li> element to my list?


So right now I have a working to-do list where in order to add a list item, you have to click a button. I wish to also allow the user to hit "enter" in order to do the same thing as the button.

Below is the js code I used to create a new li element and append it to my list.

function newElement(){
    var li = document.createElement('li');
    var inputValue = document.getElementById("myInput").value;
    li.appendChild(document.createTextNode(inputValue));
        if (inputValue === '') {
        alert("You must write something!");
      } else {
        document.getElementById("list").appendChild(li);
      }

    document.getElementById("myInput").value = "";

This is my HTML code for the button that runs the newElement() function above.

<input type ="text" id="myInput"  placeholder="Type Task Here" >
        <button class="submitButton" type="button" onclick="newElement()">Add To List</button>

Solution

  • Use keydown event and check the keyCode

    document.addEventListener("keydown", function (event) {
      if (event.keyCode === 13) {
        newElement();
      }
    });
    

    Or if you just want this behavior on the input, try to add the event listener on the input only

    document.querySelector("input").addEventListener("keydown", function(event) {
      if (event.keyCode === 13) {
        console.log("Enter key detected.")
      }
    });
    <input type="text" placeholder="Type and Enter" />