In JavaScript, triggering an action by pressing the enter key

My latest project involves creating a JavaScript-based 'to-do list' where users can add tasks by pressing the enter key, but unfortunately, I'm facing some issues with my current code. Any suggestions or advice would be greatly appreciated! Thanks.

EDIT: Included below are links to my JavaScript, HTML, and CSS files

EDIT II: Here are the specific instructions for the project: 1. Clear the input field after adding a new item. 2. Enable the enter key to trigger the same action as clicking the plus button. 3. Validate that the user actually inputs something before adding it to the list. 4. Implement a feature that allows users to change the title when clicking on the heading, ensuring they provide an input before making modifications. https://i.sstatic.net/945os.png

window.addEventListener('load', function(){

var todos = document.getElementsByClassName('todo-item');
var removes = document.getElementsByClassName('remove');
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);

function toggleCompleted(e) {
console.log('=' + e.target.className);
if(e.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(e.target.className.indexOf('completed'));
if(e.target.className.indexOf('completed') > -1) {
console.log(' ' + e.target.className);
e.target.className = e.target.className.replace(' completed', '');
} else {
console.log('-' + e.target.className);
e.target.className += ' completed';
}
}

function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));

}

function valueField(input,val){
if(input.value == "")
input.value=val;

}

function clearField(input,val){
if(input.value == val)
input.value="";
}

function removeItem(e) {
if(e.target.className.indexOf('remove') < 0) {
return;
}

function handle(e){
var keycode 
if(e.keyCode === ""){
}
return false;
}
var el = e.target.parentNode;
el.parentNode.removeChild(el);
}

});
body {
  background-color: #BCDBF2;
  font-family: Helvetica, Arial, sans-serif;
}

body > div {
  width: 300px;
  margin:50px auto;
}

h1 {
text-align: center;
}

.todo-list {
  list-style: none;
  padding: 0px;
}

.todo-item {
  border: 2px solid #444;
  margin-top: -2px;
  padding: 10px;
  cursor: pointer;
  display: block;
  background-color: #ffffff;
}
.todo-new {
  display: block;
  margin-top: 10px;
}

.todo-new input[type='text'] {
  width: 260px;
  height: 22px;
  border: 2px solid #444;
}

.todo-new a {
  font-size: 1.5em;
  color: black;
  text-decoration: none;
  background-color: #ffffff;
  border: 2px solid #444;
  display: block;
  width: 24px;
  float: right;
  text-align: center;
}

.todo-new a:hover {
  background-color: #0EB0dd;
}

.remove {
  float: right;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 0.8em;
  color: #dd0000;
}

.remove:before {
  content: 'X';
}

.remove:hover {
  color: #ffffff;
}

.todo-item::after:hover{
  background-color: #dd0000;
  color: white;
}

.todo-item:hover {
  background-color: #0EB0FF;
  color: white;
}

.completed {
  text-decoration: line-through;
  opacity: 0.5;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 18 - Event Delegation</title>
<link rel='stylesheet' href='main.css'/>
</head>
<body>
<div>
<h1>To-Do List</h1>
<ul class='todo-list'>
<li class='todo-item'>4L 2% Milk
<span class='remove'></span></li>
<li class='todo-item'>Butter, Unsalted
<span class='remove'></span></li>
<li class='todo-item'>Dozen Eggs
<span class='remove'></span></li>
<li class='todo-item'>Walk the dog
<span class='remove'></span></li>
<li class='todo-item'>Cut the lawn
<span class='remove'></span></li>
<li class='todo-item'>Laundry
<span class='remove'></span></li>
<li class='todo-new'>
<input id='new-item-text' type='text'/>
<a id='add-item' href='#'>+</a>
</li>
</ul>
</div>
<script src='main.js'></script>
</body>
</html>

Answer №1

If you need to find the key code for the "enter" button, one helpful resource is the MDN KeyboardEvent:keyCode page. Once you have that information, you can create a function like this:

var ENTER = 13;
function checkEnterKey(e){
    if(e.keyCode === ENTER){
      // Add your desired functionality here
    }
    return false;
}

Answer №2

To enable the onkeypress event on an HTML element, such as the input text, you can do it like this:

<input id='new-item-text' type='text' onkeypress="return handle(event)" /> 

Additionally, you have the option to assign the event to the <body> or other HTML elements. The event registration can be done using HTML or through Javascript.

Using HTML:

<element onkeypress="myScript">

Using JavaScript:

object.onkeypress=function(){myScript};

If you wish to learn more about this event, refer to this documentation.

Remember that the handle function should be globally declared (outside the load event).

Lastly, ensure you filter out the enter key with e.keyCode === 13. It's crucial to note that this value is a Number, not a String.

I've included all the code below which you can view and run (the example triggers when pressing enter in the input text).

Hopefully, this information proves helpful.


All Code Snippets

window.addEventListener('load', function() {

  var todos = document.getElementsByClassName('todo-item');
  var removes = document.getElementsByClassName('remove');
  document.getElementById('add-item').addEventListener('click', addItem, false);
  document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
  document.querySelector('.todo-list').addEventListener('click', removeItem, false);

  function toggleCompleted(e) {
    console.log('=' + e.target.className);
    if (e.target.className.indexOf('todo-item') < 0) {
      return;
    }
    console.log(e.target.className.indexOf('completed'));
    if (e.target.className.indexOf('completed') > -1) {
      console.log(' ' + e.target.className);
      e.target.className = e.target.className.replace(' completed', '');
    } else {
      console.log('-' + e.target.className);
      e.target.className += ' completed';
    }
  }

  function addItem() {
    var list = document.querySelector('ul.todo-list');
    var newItem = document.getElementById('new-item-text').value;
    var newListItem = document.createElement('li');
    newListItem.className = 'todo-item';
    newListItem.innerHTML = newItem + '<span class="remove"></span>';
    list.insertBefore(newListItem, document.querySelector('.todo-new'));

  }

  function valueField(input, val) {
    if (input.value == "")
      input.value = val;

  }

  function clearField(input, val) {
    if (input.value == val)
      input.value = "";
  }

  function removeItem(e) {
    if (e.target.className.indexOf('remove') < 0) {
      return;
    }

    var el = e.target.parentNode;
    el.parentNode.removeChild(el);
  }

});

function handle(e) {
  if (e.keyCode === 13) {
    console.log("Doing something");
  }
  return true;
}
body {
  background-color: #BCDBF2;
  font-family: Helvetica, Arial, sans-serif;
}
body > div {
  width: 300px;
  margin: 50px auto;
}
h1 {
  text-align: center;
}
.todo-list {
  list-style: none;
  padding: 0px;
}
.todo-item {
  border: 2px solid #444;
  margin-top: -2px;
  padding: 10px;
  cursor: pointer;
  display: block;
  background-color: #ffffff;
}
.todo-new {
  display: block;
  margin-top: 10px;
}
.todo-new input[type='text'] {
  width: 260px;
  height: 22px;
  border: 2px solid #444;
}
.todo-new a {
  font-size: 1.5em;
  color: black;
  text-decoration: none;
  background-color: #ffffff;
  border: 2px solid #444;
  display: block;
  width: 24px;
  float: right;
  text-align: center;
}
.todo-new a:hover {
  background-color: #0EB0dd;
}
.remove {
  float: right;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 0.8em;
  color: #dd0000;
}
.remove:before {
  content: 'X';
}
.remove:hover {
  color: #ffffff;
}
.todo-item::after:hover {
  background-color: #dd0000;
  color: white;
}
.todo-item:hover {
  background-color: #0EB0FF;
  color: white;
}
.completed {
  text-decoration: line-through;
  opacity: 0.5;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Lab 18 - Event Delegation</title>
  <link rel='stylesheet' href='main.css' />
</head>

<body>
  <div>
    <h1>To-Do List</h1>
    <ul class='todo-list'>
      <li class='todo-item'>4L 2% Milk
        <span class='remove'></span>
      </li>
      <li class='todo-item'>Butter, Unsalted
        <span class='remove'></span>
      </li>
      <li class='todo-item'>Dozen Eggs
        <span class='remove'></span>
      </li>
      <li class='todo-item'>Walk the dog
        <span class='remove'></span>
      </li>
      <li class='todo-item'>Cut the lawn
        <span class='remove'></span>
      </li>
      <li class='todo-item'>Laundry
        <span class='remove'></span>
      </li>
      <li class='todo-new'>
        <input id='new-item-text' type='text' onkeypress="return handle(event)" />
        <a id='add-item' href='#'>+</a>
      </li>
    </ul>
  </div>
  <script src='main.js'></script>
</body>

</html>

Answer №3

In my opinion, the key code that corresponds to the Enter key is 13 as demonstrated below.

function handleKey(e){
    if(e.keyCode === 13){
    }
    return false;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to deploy Firebase functions following the addition of an NPM package

Scenario: I recently tried integrating Taiko into my Firebase web application, similar to Puppeteer. It's worth mentioning that Taiko downloads Chromium for its operations. Challenge: Ever since then, none of my functions are deploying successfully. ...

There was a hiccup in the camera positioning as the tweening began

I've been working on a basic program that involves tweening the camera to a specific position. The functionality works smoothly for the most part, however, I encounter some glitches at the start of the transition when trying to pan the camera using or ...

"Error in Node.js and Express: The variable 'next' has not been defined

I encountered the Error: next is not defined message, but I am unsure of where in my codebase this error is originating from. https://i.sstatic.net/29ZPT.png Here is a snippet of my code: server.js // Server configuration and setup details are here // P ...

Pairing ID_x with ID_x or iterating through IDs with an increment of +i

I've been trying to work on something similar, but I keep running into roadblocks. Essentially, my issue lies within a for loop $(document).ready(function() { var foo = function() { for (var i = 0; i < 10; i++) { $('#event_&a ...

Tips for enabling auto-scroll feature in MuiList

Currently, I am working on a chat window component that utilizes Material UI for styling. I expected that setting a height or max-height on either the MuiList or MuiBox encapsulating the list would automatically scroll to the new message when it's sen ...

When attempting to achieve a CSS percent width, the output is given in pixels instead. I am in search of a solution where the percentage remains the same as the

My styling is set as a percentage, like this: <style> #somediv {width:70%} </style> <div id="somediv"></div> jQuery's css() function returns the result in pixels $(document).ready(function(){ var css = $("#somediv").css( ...

Loading identical code in two different div elements

I am in the process of designing a comprehensive resource database featuring a side-scrolling container. Once a user clicks on a thumbnail within the container, the contents of a corresponding div will fade in and display specific category content. Each di ...

Encountering Storage Access Problem on Android following upgrade to API 33

I am currently working on an Ionic, Angular, and Capacitor application where I am utilizing the Cordova-diagnostic-plugin to download images onto a device. However, since updating to Android API 33, I have encountered an issue. Issue Description: Once I ...

My React component is experiencing issues with the Console.log functionality

Utilizing React for a component, I have incorporated a button that triggers a function 'myFunction' upon clicking, which essentially executes a console.log command. https://i.sstatic.net/mc8wu.png Despite compiling the code without any errors in ...

Navigating between different components in React Router V4 allows for seamless transitions without having to reload the

I am currently learning React with React Router V4 and I have a specific scenario in mind that I would like to achieve, possibly illustrated by the image below: Click on the "Next" button Trigger a click event to Component A ("button got clicked") Upon c ...

Angular: Enhancing View Attribute by Eliminating Extra Spaces

I'm using an ng repeat directive to dynamically set the height in my code. <ul> <li ng-repeat="val in values" height-dir >{{val.a}}</li> </ul> app.directive('heightDir',function(){ return { restrict: ' ...

What is the best way to store and retrieve all the variable data from a .js file on a user's device?

I'm looking for a way to save and load multiple variables in JavaScript that determine a "save" state. These variables are stored in a file named "variables.js." Is there a simple method to easily save all the information in this file and then load i ...

Node.js provides a variety of ways to serve files, including determining where and how they are

Currently, I am diving into the world of node.js/express.js and going through various tutorials to enhance my understanding. However, coming from a background with simple apache logic, I find myself confused by the logic presented in node.js/express.js. Ca ...

What is the best way to efficiently retrieve gzipped XML content using JavaScript?

Is there a more efficient way to access a large gzipped XML file from JavaScript, specifically within Greasemonkey? The server does not provide a Content-Encoding header, and the Content-Type is "application/x-gzip," preventing Firefox from automatically i ...

Creating custom events in a JavaScript constructor function

Just beginning to learn JavaScript. I have a custom function that I want to assign events to in the constructor. var myFunction = function(){ /* some code */ } myFunction.prototype.add=function(){ /* adding item*/ } Now I am looking to add an event to ...

Unable to transform SVG files in Next.js Jest version 28

Currently, my setup involves Next.js version 12.0.7, Jest version 28.1.0, and the use of the next-react-svg library for importing SVG files into components. The configuration in my jest.config.js file looks like this: // jest.config.js const nextJest = re ...

What specific checks and alerts are triggered by React.StrictMode?

When utilizing React.StrictMode and React.Fragment, according to the React documentation: Both Fragment and StrictMode do not display any visible UI. Instead, they trigger additional checks and warnings for their child components. Question: What specif ...

Stop the removal of the CSS content property

When a user enters and re-enters their password, I have a form that checks the strength of the password and displays text accordingly. However, I noticed that if a user makes a mistake and uses the backspace to re-enter the password, the text from data-tex ...

Encountering a 401 error without proper authorization in a MERN application

Currently, I am working on developing a web application using the MERN stack. The backend API that I have created is functioning perfectly fine on Postman. However, I am facing an issue when trying to connect the backend with the frontend and submit data t ...

Combining ExtJS Paging with Dropdown Selection

Having an issue with a combo box created using the ExtJS framework. The pagination feature is not working correctly. Can anyone provide assistance with this? var store = new Ext.data.ArrayStore({ fields: ['id'], pageSize:1, data : ...