What is the best way to capture the input value upon pressing the "Enter" key?

My first question here is about implementing the addtodo(todo) code. After trying it out successfully, I wanted to make it work when typing and pressing enter. However, despite attempting some other methods, I couldn't get it to work. I didn't receive any error messages in Chrome or VSCode. As a beginner, my code might be messy. How much more detail do you need? If you don't submit, I'll start writing a story (no kidding).

const dateElement = document.querySelector('.date');
        const input = document.querySelector('#text-bar')
        const list = document.querySelector('.input')
        //date stuff
        
        const options = {
          weekday: "long",
          month: "short",
          day: "numeric"
        };
        const today = new Date();
        
        dateElement.innerHTML = today.toLocaleDateString("en-US", options);
        
        function toodoo(todo) {
          const item =
            ` 
           <li><i class="far fa-circle" id="circle"></i></li> 
        <li>${todo}</li>
        <li>  <button class="edit">edit</button></li>
        <li> <button class="remove">remove</button></li>
            `;
          const position = "beforeend";
          list.insertAdjacentHTML(position, item);
        }
        
        document.addEventListener("enter", function(event) {
          if (event.keycode == 13) {
            const todo = input.Value;
            if (todo) {
              toodoo(todo);
            }
          }
        });
* {
          background-color: coral;
          margin: 0px;
        }
        
        body {
          text-align: center;
          margin: 100px;
        }
        
        .middle-space {
          height: 70vh;
          border: 2px solid rgba(126, 125, 125, 0.671);
          width: 30%;
          margin: auto;
          background-color: white;
        }
        
        #text-bar {
          width: 30%;
          border: 2px solid black;
          height: 3vh;
          margin-left: 25px;
          border-radius: 25px;
          background-color: white;
        }
        
        h1 {
          background-image: url('download (1).jpeg');
          width: 30%;
          padding-top: 8vh;
          padding-bottom: 2vh;
          text-align: left;
          font-size: 25px;
          margin: auto;
          border: 2px solid rgba(126, 125, 125, 0.671);
          background-repeat: no-repeat;
          background-size: cover;
          background-position: center;
          background-color: white;
        }
        
        #button {
          color: greenyellow;
          font-size: 25px;
        }
        
        @media(max-width:600px) {
          .middle-space {
            width: 100%;
          }
          #text-bar {
            width: 80%;
            margin: 0px;
          }
          h1 {
            width: 100%;
          }
        }
        
        /* Remove Edit */
        
        .input li {
          list-style: none;
          display: inline;
          list-style-type: none;
          padding-left: 10px;
          background-color: white;
        }
        
        .input {
          text-align: left;
          margin: auto;
          background-color: white;
          border-bottom: 2px solid black;
          border-radius: 24px;
          margin-top: 20px;
          padding-bottom: 10px;
        }
        
        #circle {
          background-color: white;
          color: greenyellow;
        }
        
        ul {
          background-color: white;
          list-style: none;
        }
        
        .edit {
          border: none;
          background-color: white;
          color: green;
          margin-left: 150px;
        }
        
        .remove {
          border: none;
          background-color: white;
          color: red;
        }
        
        .middle-space ul {
          padding: 0px;
          margin: 0px;
        }
<!DOCTYPE html>
          <html lang="en">
          
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>test</title>
            <link rel="stylesheet" href="style.css">
          
            <script src="https://use.fontawesome.com/releases/v5.15.1/js/all.js"></script>
          </head>
          
          <body class="body">
            <h1 class="date">h</h1>
            <div class="middle-space">
              <div class="input">
                <ul>
                  <!--              <li><i class="far fa-circle" id="circle"></i></li> 
              <li>drinkcoffee</li>
               <li>  <button class="edit">edit</button></li>
               <li> <button class="remove">remove</button></li>-->
                </ul>
              </div>
            </div>
          
            <div class="input-field"><input type="text" id="text-bar" placeholder="write stuff or something magic will happen"> <i class="fas fa-plus-circle" id="button"></i></button>
            </div>
            <script src="test.js"></script>
          </body>
          
          </html>

Answer №1

Inside the enter-event function, declare a variable called 'input'. Upon the DOM being fully loaded, the script retrieves the value of input (which is currently empty) and does not perform any action with it. However, when you press Enter, the empty value is assigned to the 'todo' variable.

Answer №2

To achieve the desired functionality, you can utilize a combination of a <form> element along with the submit event.

Note that there is no enter event available in JavaScript. Instead, consider using the keydown and keyup events for your implementation.

Incorporated below is a <form> element enclosing the <input> element, along with a

<button type="submit">
element to trigger form submission through a button click.

Ensure to listen to the submit event on the form. In the event handler, make sure to prevent the default form submission behavior by calling event.preventDefault(). This will enable you to customize the form submission process according to your requirements.

const dateElement = document.querySelector('.date');
const input = document.querySelector('#text-bar');
const list = document.querySelector('.input');

// Accessing the form element.
const form = document.querySelector('#todo-form');

// Date configurations.
const options = {
  weekday: "long",
  month: "short",
  day: "numeric"
};
const today = new Date();

dateElement.innerHTML = today.toLocaleDateString("en-US", options);

function createTodo(todo) {
  const item = `
    <li>
      <i class="far fa-circle" id="circle"></i>
    </li> 
    <li>${todo}</li>
    <li>  
      <button class="edit">edit</button>
    </li>
    <li>
      <button class="remove">remove</button>
    </li>
  `;
  const position = "beforeend";
  list.insertAdjacentHTML(position, item);
}

// Listen for submit event on form triggered by button click or enter key press.
form.addEventListener('submit', function(event) {
  event.preventDefault(); // Prevent actual form submission.
  const todo = input.value; // Pay attention to lowercase 'v'.
  if (todo) {
    createTodo(todo);
  };
});
* {
  background-color: coral;
  margin: 0px;
}

body {
  text-align: center;
  margin: 100px;
}

.middle-space {
  height: 70vh;
  border: 2px solid rgba(126, 125, 125, 0.671);
  width: 30%;
  margin: auto;
  background-color: white;
}

#text-bar {
  width: 30%;
  border: 2px solid black;
  height: 3vh;
  margin-left: 25px;
  border-radius: 25px;
  background-color: white;
}

h1 {
  background-image: url('download (1).jpeg');
  width: 30%;
  padding-top: 8vh;
  padding-bottom: 2vh;
  text-align: left;
  font-size: 25px;
  margin: auto;
  border: 2px solid rgba(126, 125, 125, 0.671);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-color: white;
}

#button {
  color: greenyellow;
  font-size: 25px;
}

@media(max-width:600px) {
  .middle-space {
    width: 100%;
  }
  #text-bar {
    width: 80%;
    margin: 0px;
  }
  h1 {
    width: 100%;
  }
}


/*remove edit*/

.input li {
  list-style: none;
  display: inline;
  list-style-type: none;
  padding-left: 10px;
  background-color: white;
}

.input {
  text-align: left;
  margin: auto;
  background-color: white;
  border-bottom: 2px solid black;
  border-radius: 24px;
  margin-top: 20px;
  padding-bottom: 10px;
}

#circle {
  background-color: white;
  color: greenyellow;
}

ul {
  background-color: white;
  list-style: none;
}

.edit {
  border: none;
  background-color: white;
  color: green;
  margin-left: 150px;
}

.remove {
  border: none;
  background-color: white;
  color: red;
}

.middle-space ul {
  padding: 0px;
  margin: 0px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>test</title>
  <link rel="stylesheet" href="style.css">

  <script src="https://use.fontawesome.com/releases/v5.15.1/js/all.js"></script>
</head>

<body class="body">
  <h1 class="date">h</h1>
  <div class="middle-space">
    <div class="input">
      <ul>
        <!--    <li><i class="far fa-circle" id="circle"></i></li> 
    <li>drinkcoffee</li>
     <li>  <button class="edit">edit</button></li>
     <li> <button class="remove">remove</button></li>-->
      </ul>
    </div>
  </div>

  <form id="todo-form">
    <div class="input-field">
      <input type="text" id="text-bar" placeholder="write stuff or something magic will happen"> 
      <button type="submit"><i class="fas fa-plus-circle" id="button"></i></button>
    </div>
  </form>
  <script src="test.js"></script>
</body>

</html>

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

Canvas Frustratingly Covers Headline

Several months ago, I successfully created my portfolio. However, upon revisiting the code after six months, I encountered issues with its functionality. Previously, text would display above a canvas using scrollmagic.js, and while the inspector shows that ...

Navigating and exploring data stored in a mongoose database

Currently, I am attempting to filter data based on a specific id (bWYqm6-Oo) and dates between 2019-09-19 and 2019-09-22. The desired result should return the first three items from the database. However, my current query is returning an empty array. I wou ...

Encountering an undefined error while attempting to retrieve an object from an array by index in Angular

Once the page is loaded, it retrieves data on countries from my rest api. When a user selects a country, it then loads the corresponding cities for that country. Everything is functioning properly up to this point, however, upon opening the page, the city ...

When attempting to pass data to a modal, an error occurs due to props being undefined. This results in a TypeError with the message "Cannot

I'm working on a product listing feature where each item displays some information along with a "more details" button. When the button is clicked, a modal window opens to show additional details of the specific product (using props to pass data betwee ...

I've been attempting to develop a React application, but I consistently encounter the following error: "npm ERR! cb() function was never invoked!"

Here is the issue at hand: HP@DESKTOP-1HP83V8 MINGW64 ~/Desktop/Web-Development (master) $ npx create-react-app my-app A new React app is being created in C:\Users\HP\Desktop\Web-Development\my-app. Packages are being installed. ...

What causes a CSS Variable to appear crossed out in the Chrome Debugger?

Currently facing a challenge with debugging an issue where certain CSS Variables are being overridden by an unknown source. It's puzzling because I cannot identify what is causing the override. When it comes to standard CSS properties (such as font-fa ...

Several queries for directions on Google Maps are resulting in the same response being returned for all requests

I've been experimenting with the Google Maps Directions service to retrieve three different travel methods for the same route (driving, walking, and bicycling). Despite successfully iterating through the array of methods and setting them in the respec ...

I require the box element within my section element to have a full-width layout

Looking at the code in the image, you can see that I am using MUI components. Within a section, there is a box containing navigation filter links. The red part represents the section, while the white inside is the navigation link bar. My goal is for this b ...

jQuery does not function properly when used with string variables

Why am I experiencing different results in Google Chrome when using a hard-coded string versus storing the same string in a variable? While the hard-coded string works properly, the same string stored in a variable does not produce the expected outcome. ...

Troubleshooting problems with data rendering in jQuery

Currently, my goal is to use JQuery to display a menu of checkboxes based on a specific template in a div. To enhance user experience, I have included a search box that will filter the menu items. However, there is an unusual issue occurring. When the men ...

The dropdown menus in Bootstrap are expanding outside the screen when opened

When I click on the dropdown in the Navbar on the right side, the menus open up far to the right and are not visible until I scroll horizontally. Here is the code snippet: <nav class="navbar navbar-expand-lg navbar-light bg-light"> < ...

The interaction of flex-box in the presence of absolute positioning

Hey everyone, I need some help understanding why the flexbox is behaving oddly in this code snippet. 1. <!DOCTYPE html> <html> <head> <style> body{ position: relative; } .container { ...

Chrome extension for AJAX with CORS plugin

Currently, I am utilizing jQuery for cross-origin AJAX requests and attempting to include headers in the request as shown below. However, I am encountering an error message stating that it is an invalid request: $.ajax({ url: address, headers:{ ...

Troubleshooting jQuery ajax data retrieval issue in Internet Explorer 8

I'm currently utilizing jQuery submit to submit form data and retrieve it. The data is returned via ajax. When the data is received, I want to display the DIV Gallery HTML. To do this: <form action="" method="post" name="view_all" id="view_all" ...

Issue with Node Canvas/Resemble.js: The image provided has not finished loading during the load operation

Recently, I encountered a challenge while trying to utilize Resemble.js in a node environment. Despite some initial complications with installing canvas/cairo due to OS X Mavericks/XQuarts and Homebrew issues, I eventually succeeded. After making signific ...

arrange elements by their relationship with parents and children using typescript and angular

Here is a list that needs to be sorted by parent and child relationships: 0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4} 1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null} 2: {id: 5, name: ...

Adjusting the gaps between each item in a list

Currently, I am working on developing a minimalist single-page website. However, I am facing challenges with spacing in the navbar section (as demonstrated below). When using an unordered list, everything looks good until the list overlaps with the centra ...

Using an npm package to include CSS styles in a stylesheet

I created an NPM package that includes a CSS file that needs to be included in my main CSS file. In a typical HTML CSS website, I would need to write @import url("./node_modules/web-creative-fonts/index.css") but what I really want is to simplify ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

Trouble with integrating HTML5 canvas from an external JavaScript file

Having trouble with storing canvas js in an external file. If the javascript responsible for drawing on the canvas is included in the html header, then the rectangle is displayed correctly. Here is the working html (javascript in html header): <!DOCT ...