devolution
devolution

Reputation: 37

How to trigger an add button with both a click and enter keyboard button?

I am working on making this ToDo app. I can add tasks by clicking on the add button, but I am unable to figure out how to also make it so that tasks can be added using the enter keyboard button.

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

  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u00D7");
  span.className = "close";
  span.appendChild(txt);
  li.appendChild(span);

Upvotes: 1

Views: 50

Answers (2)

Phil
Phil

Reputation: 164890

Put the elements within a <form> and bind to the submit event. Both of clicking on a submit button or hitting Enter in a text field will submit the form

// Minified your function for brevity
function newElement(){var e=document.createElement("li"),t=document.getElementById("myInput").value,n=document.createTextNode(t);e.appendChild(n),""===t?alert("You must write something!"):document.getElementById("myUL").appendChild(e),document.getElementById("myInput").value="";var d=document.createElement("SPAN"),m=document.createTextNode("×");d.className="close",d.appendChild(m),e.appendChild(d)}

document.getElementById("form").addEventListener("submit", e => {
  e.preventDefault()
  newElement()
})
<form id="form">
  <input id="myInput">
  <button type="submit">➕</button>
</form>
<ul id="myUL"></ul>

Upvotes: 1

Mamun
Mamun

Reputation: 68923

You can call the function on keydown event by checking the KeyboardEvent.code value:

Demo:

document.getElementById("myInput").addEventListener("keydown", function(event) {
  if(event.code == "Enter"){
    newElement()
  }
}, true);

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

  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u00D7");
  span.className = "close";
  span.appendChild(txt);
  li.appendChild(span);
}
<input id="myInput"/>
<ul id="myUL"></ul>

Upvotes: 1

Related Questions