Trying to get enter key to trigger

Viewed 51

I'm trying to make a grocery list app that functions as a to-do list. I've got most of the basics down for it so far. I've got a button that takes the input field value, adds it to an array, and displays it to the page. However, I would also like for this to trigger by pressing the enter key. I've given it a shot and so far I've had no luck. I'm not sure why, but instead of just triggering from the enter key, it is creating a new item on the page with every keypress. I would also like to know how to make it so that if the input field is empty, then nothing happens upon click or enter keypress.

let addButton = document.getElementById('add-button');
addButton.addEventListener('click', add);

let addInput = document.getElementById('add-input');
addInput.addEventListener('keydown', add);

//let removeButton = document.getElementById('remove-button');
//removeButton.addEventListener('click', remove);

let groceryList = []

function add() {
  groceryInput = addInput.value;
  groceryList.push(groceryInput);
  addInput.value = '';
  displayGroceries();
}

function remove(event) {
  let position = event.currentTarget.id;
  groceryList.splice(position, 1);
  displayGroceries();
}

function displayGroceries() {
  let groceryUl = document.getElementById('grocery-ul');
  groceryUl.innerHTML = '';

  for (var i = 0; i < groceryList.length; i++) {
    let groceryLi = document.createElement('li');
    groceryLi.innerHTML = groceryList[i];
    groceryUl.appendChild(groceryLi);
    let removeButton = document.createElement('button');
    removeButton.innerText = "Remove";
    removeButton.addEventListener('click', remove);
    removeButton.id = i;
    groceryLi.appendChild(removeButton);

    if (add.keyCode === 13) {
      add();
    }
  }
}
<div class="container">
  <h1>Grocery List</h1>
  <input id="add-input" placeholder="Add Groceries" autocomplete="off">
  <button id="add-button">Add</button>
  <!--<button id="remove-button">Remove</button>-->
  <div>
    <ul id="grocery-ul">

    </ul>
  </div>

2 Answers

You use 'keydown' event which fire when any key is pressed not only enter key. To call add function only for enter press you must customize it. Like -

if(key.which == 13) {
  add();
}

And to prevent post empty input value you must check it.

if(groceryInput) {
   groceryList.push(groceryInput);
   addInput.value = '';
   displayGroceries();
}

working Fiddle - https://jsfiddle.net/0xtzb5mg/1/

'keydown' is an event which will work if any key is pressed. You have to specify the keyCode of the key if you need an action to be taken when a particular key is pressed.

In your requirement, the enter key is used and the keyCode for enter key is 13.

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

You can check the keycode for all the keys in this link http://gcctech.org/csc/javascript/javascript_keycodes.htm

Related