jQuery enter key not calling function

Viewed 55

I have an input that when a button is clicked, adds the value to a list. I'm trying to do the same when the enter key is pressed.

I have the code for the enter key working in long form (ie. I'm repeating the functions parameters within the enter key function) but I want to shorten the code and simply call the function when I click the button or press enter.

The .click works fine when calling the function but the enter key does not. It's getting through to consol .log(2) but isn't calling the function.

 HTML
    <div id="newItemWrapper">
        <input id="newItem" placeholder="Add a new item">
        <br>
        <h6 id="newItemBtn" class="btn btn-primary">Add new item</h6>
        <br>
        <h6 id="save" class="btn btn-success">Save</h6>
        <h6 id="clear" class="btn btn-warning">Clear</h6>
        <p class="card-text"><small id="lastUpdated" class="text-muted">Last updated </small></p>
        
      </div>`

jQuery

 (function(){


  function addNewItem(){
    let newInput = $("#newItem").val();

    $("#stillToDo").append("<li>" + newInput + "</li>");
    $("#newItem").val("");
    $("#lastUpdated").text("Last updated " + Date());
  };


  $("#newItemBtn").click(addNewItem);

jQuery Does not work

  $("#newItem").keypress (function (e){
    if (event.which == 13) {
      console.log (1);
      (addNewItem);
      console.log(2);
  }
});
});`


**jQuery long form which DOES work**

        $("#newItem").keypress(function addNewItem(event){
      let newInput = $("#newItem").val();
      let keycode = (event.keyCode ? event.keyCode : event.which);
  
      if(keycode == '13'){
        $("#stillToDo").append("<li>" + newInput + "</li>");
        $("#newItem").val("");
        $("#lastUpdated").text("Last updated " + Date()); 
  
      }
    });
0 Answers
Related