input value does not change when the "keyup" event is triggered

I'm encountering an issue with the code below. The code is for a simple To Do app using Javascript. I followed a tutorial step by step, but my app isn't functioning as expected. When I press the enter key, the input value should be added to the list, but it's not happening. I've checked the code multiple times and can't seem to find any mistakes.

Even when I manually call the function addToDo("read");, it works fine. However, pressing the enter button doesn't trigger the function. Any suggestions or advice would be greatly appreciated.

document.addEventListener("keyup", function(event) {
    if (event.key === 13) {
        const toDo = input.value;
        if (toDo) {
            addToDo(toDo);
        } //end if toDo
    } // end if event.key

});

Answer №2

function createToDo(item) {
  console.log(item);
}

document
  .querySelector('#input-field')
  .addEventListener('keyup', function (event) {
    if (event.key === 'Enter') {
      const newItem = event.target.value;

      if (newItem) {
        createToDo(newItem);
      } //end if newItem
    } // end if event.key
  });
<input type="text" id="input-field>

Answer №3

event.key value is a string. Instead of using the keyCode 13, try using 'Enter'. The keyCode returns numbers when accessing event.keyCode.

document.addEventListener("keyup", function(event){
console.log(event.keyCode);
if(event.key === 'Enter'){
    //const toDo = input.value;
    //if(toDo){
      //  addToDo(toDo);
console.log('Enter')
//}//end if toDo
}// end if event.key
})
<div>Press 'Enter' key on your keyboard</div>

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

Executing an Ajax request that invokes a PHP function

After receiving valuable information in response to my previous inquiry through this link, I took the initiative to create a code that would notify me via email if it is discovered on another website. Below is the JavaScript code designed for potential co ...

Using the html5-canvas element to drag connected lines

Here is an example of creating four points and connecting them: sample. My goal is to make it possible to drag the entire line connection when clicking on it, but when clicking on a circle, only that specific circle should be extended (already implemented ...

Chat lines in Chrome displaying double entries - troubleshooting needed

I developed a chat plugin for my website with a simple HTML structure: <div id="div_chat"> <ul id="ul_chat"> </ul> </div> <div id="div_inputchatline"> <input type="text" id="input_chatline" name="input_chatline" val ...

Create a dynamic calendar by integrating dates with Javascript and an HTML table

Recently, I decided to delve into web design again and embark on a challenging project for my father's baseball business. The main task at hand is creating a detailed calendar using HTML tables. After spending a considerable amount of time perfecting ...

What steps do I need to take to deploy my React app onto a server?

I recently completed creating my first website with React and now I want to upload it to my server (HostGator). Can anyone guide me on how to do that? Thank you. ...

Increasing the upward motion of the matrix raining HTML canvas animation

Recently, I've been experimenting with the Matrix raining canvas animation here and I was intrigued by the idea of making it rain upwards instead of downwards. However, my attempts to achieve this using the rotate() method resulted in skewing and stre ...

What is the process for adding an event listener in React?

Currently, I am working on a chat application that involves both users and agents. I am facing an issue where I need to retrieve messages when the agent responds using a separate Rainbow UI. According to the documentation, this can only be achieved using a ...

Limit DerbyJS to re-rendering specific DOM elements

Currently, DerbyJS (visit http://derbyjs.com) functions by replacing everything in the body tag of the document each time a link is clicked. Is there a way to utilize the template, but replace only the content inside #main-content instead of refreshing th ...

DataTables.Net Buttons not appearing in the interface

I have a basic MVC project that utilizes BootStrap4 and dataTables.Net. When the page loads, an Ajax call is made to fetch data for a table. However, despite following the documentation, I'm unable to get the buttons to display on the page. Everything ...

Tips for incorporating MUI into your Redwood JS project

Trying to integrate MUI into Redwood JS has been a challenge for me. I attempted to run the following command in the project directory: yarn add @mui/material Unfortunately, an error message appeared in the console stating: An error Running this command w ...

Display animated GIFs in the popular 9Gag format

Is there a way to display a GIF file after clicking on a JPG file, similar to the functionality on 9Gag.com? I am currently using timthumb.php for displaying JPG images. https://code.google.com/p/timthumb/ Below is the code snippet: <div class="imag ...

Enhance the appearance of the <td> <span> element by incorporating a transition effect when modifying the text

I need help with creating a transition effect for a span element within a table cell. Currently, when a user clicks on the text, it changes from truncated to full size abruptly. I want to achieve a smooth growing/scaling effect instead. You can view an exa ...

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

Adjust the size of the font in your Bootstrap Table

I've been utilizing the Bootstrap table feature and it's been fantastic, but I've encountered an issue with changing the font size. I've referred to the example on , however no matter what adjustments I make to the size, it doesn' ...

Is there a way to ensure that a certain block of code in Typescript is executed only after an API call has been completed?

When making an API call, I need the code after the call to wait until the API call finishes. In my function called this.api_call, it calls the API and only returns an array returnValue once the call is complete. let returnValue = this.api_call(data); // ...

Pusher authentication issue: socket ID not defined

I am currently facing an issue while trying to establish a private channel for users to transmit data to my node.js server. Upon making the request, I encounter an error where pusher:subscription_error is returned with the error code 500. Upon checking my ...

Applying conditional logic within computed properties results in a failure to update

I have two different fiddles: Fiddle A and Fiddle B (both using Vuejs version 2.2.4) In my code, I have a computed property that can be changed programmatically by utilizing the get and set methods. Expectations for the Computed Property: If the def ...

Code functions properly on local host but encounters errors when deployed to live server

My comment system was working fine on localhost using PHP, AJAX and JavaScript. However, after transferring my website to a live server, the code does not seem to be functioning properly. Here is an example of the script: <script type="text/javascript ...

Asynchronous data fetching with React Hook useEffect does not properly populate the tooltip in Material UI component

After using useEffect to fetch data, I encountered a problem in passing the data to my component. Here is some of my code: User Data Types (UPDATED) export interface IUser { display_name: string; id: string; images: Image[]; } expo ...

I am uncertain about whether it would be better to utilize URL path parameters or query parameters for filtering on the back-end of the application

Suppose I am trying to retrieve all car models from a specific brand. This can be achieved by utilizing URL path parameters or query parameters as shown below: router.get('/modelsByBrand', modelController.getModelsByBrand); To make the GET reque ...