Search code examples
javascripthtmlvisual-studiojavascript-objects

How to use enter button from keyboard as submit


I'm making a todo list using javaScript,HTML and CSS and for insert any element we have to click on submit(add) button but i want that when we press enter button from keyboard the element will insert or the submit button will press and i don't have any idea how to do that because i am new in javascript


Here is the Code


HTML

<DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
</head>
<body>
<input id="task"><button id="add">Add</button>
<hr>
<div id="todos"></div>

<script src="nv.js"></script>
</body>
</html>

Java Script

function get_todos() {
  var todos = new Array;
  var todos_str = localStorage.getItem('todo');
  if (todos_str !== null) {
      todos = JSON.parse(todos_str); 
  }
  return todos;
}

function add() {
  var task = document.getElementById('task').value;

  var todos = get_todos();
  todos.push(task);
  localStorage.setItem('todo', JSON.stringify(todos));

  show();

  return false;
}

function remove() {
  var id = this.getAttribute('id');
  var todos = get_todos();
  todos.splice(id, 1);
  localStorage.setItem('todo', JSON.stringify(todos));

  show();

  return false;
}

function show() {
  var todos = get_todos();

  var html = '<ul>';
  for(var i=0; i<todos.length; i++) {
      html += '<li>' + todos[i] + '<button class="remove" id="' + i  + '">x</button></li>';
  };
  html += '</ul>';

  document.getElementById('todos').innerHTML = html;

  var buttons = document.getElementsByClassName('remove');
  for (var i=0; i < buttons.length; i++) {
      buttons[i].addEventListener('click', remove);
  };
}

document.getElementById('add').addEventListener('click', add);
show();

Thanks


Solution

  • Need to add onkeypress event to the task input as below:-

    HTML

    <input id="task" onkeypress="enterToSubmit(event)">
    

    Javascript:

    function enterToSubmit(event){
        var key = event.keyCode;
        if(key===13){
            add();
        }
    }