0

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>
  • The best way would probably be to handle the form `submit` event, and call `newElement()` there. Then you can also remove the `onclick` from the button. You likely want to [use `event.preventDefault()`](https://stackoverflow.com/questions/7410063/how-can-i-listen-to-the-form-submit-event-in-javascript) too, but you haven't provided your whole form/HTML (or did you?), so it's not clear how your form is currently set up. – WOUNDEDStevenJones Mar 08 '21 at 22:24

1 Answers1

0

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" />
lastr2d2
  • 3,604
  • 2
  • 22
  • 37
  • it should work, added a snippet in place for the second one. maybe check elsewhere in your REAL code – lastr2d2 Mar 08 '21 at 22:48
  • Thank you! I played around with your code and changed document.querySelector to document.getElementById and it worked! Thank you!!!! – Erin Woodard Mar 08 '21 at 22:51