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

The Ajax call was successful but the callback function failed to return

I've been encountering some challenges with a small application I'm developing. After successfully setting it up to automatically populate one field with the same value entered in another field, I decided to integrate an AJAX request into the scr ...

Converting a JSON object with numerical keys back to its original form

Recently diving into JavaScript programming, I find myself struggling with reversing the keys of a single JSON object. Here is the specific object that I'm attempting to reverse: {70: "a", 276: "b ", 277: "c ", 688: "d", 841: "e", 842: "f", 843: ...

Javascript text validation is malfunctioning as the alert message fails to appear

Looking for a simple form validation script: <script language=”javascript”> function checkForm(register) { if (""==document.forms.register.FNAME.value){ alert("Please fill out this field!"); document.forms.register.FNAME.focus( ...

What is the method by which Morgan middleware consistently displays the output on the console following the execution of all other middleware

Utilizing the express library along with the logging library known as morgan Provided below is a snippet of working code that can be used to reproduce this in nodejs: const express = require('express') const morgan = require('morgan') ...

Smooth scrolling problems arise when a page loads and the offset jumps unexpectedly when the ID and hash are set to the same value

UPDATE: I'm considering converting this to jQuery, similar to the example here: http://davidwalsh.name/mootools-onload-smoothscroll Situation: Working on a Wordpress site with subnav navigation set for smooth scrolling down the page using /page/#idna ...

Instructions for showcasing a 404 error page in the event that a back-end GET request to an API fails due to the absence of a user. This guide will detail the process of separating the

I am currently working on an application that combines JavaScript with Vue.js on the front-end and PHP with Laravel on the back-end. When a GET request is made from the front-end to the back-end at URL /getSummoner/{summonerName}, another GET request is t ...

Aligning a navigation bar with a hamburger menu in the center

I recently implemented a hamburger menu with some cool animations into my site for mobile devices. Now, I am facing the challenge of centering the menu on desktop screens and it's proving to be tricky. The positioning is off, and traditional methods l ...

Including a hyperlink in VUE Bootstrap for seamless user navigation

Why does this always drive me crazy? I'm determined to include an external link () and an image(enter image description here) on my portfolio page within the title of the project. main.js { id: 18, url: 'single-portfolio. ...

I am selecting specific items from a list to display only 4 on my webpage

I am trying to display items from a list but I only want to show 4 out of the 5 available items. Additionally, whenever a new item is added, I want it to appear first on the list, with the older items following behind while excluding the fifth item. Despi ...

Is there a way to implement this media query within my JavaScript code?

I am attempting to make my website recognize when the screen width surpasses 1096px in order to apply some CSS styling. Below is the code I'm using: var mq = window.matchMedia('@media all and (max-width: 1096px)'); if(mq.matches) { wind ...

When jQuery is combined with extending Object.prototype, the result is an error message that states, "c.replace is not

In my open source project, I am utilizing jQuery 1.5 and the following snippet is included in my JavaScript code: /** * Object.isEmpty() * * @returns {Boolean} */ Object.prototype.isEmpty = function () { /** * @deprecated Since Javascript 1.8 ...

Easy PHP navigation options

Creating a basic PHP page with includes is proving challenging when it comes to navigating URLs using '../' to find the correct path to the folder. Is there a straightforward way to set up a simple PHP navigation without involving MySQL or other ...

Designing a button component with text

Exploring My Demo Page, I am attempting to design a button that will serve as a closure mechanism for modals. The code snippet I experimented with is as follows: x=document.createElement('button'); x.className='superclose'; Referencin ...

How to send emails with attachments using WordPress?

Looking for assistance in sending emails with attachments using Wordpress. I am struggling and believe there might be something missing in my code. Any help would be greatly appreciated! :) Below is the code spread across two files: Name (required)<b ...

Removing invalid characters in a *ngFor loop eliminates any elements that do not meet the criteria

I am facing an issue with my *ngFor loop that is supposed to display a list of titles. fetchData = [{"title":"woman%20.gif"},{"title":"aman",},{"title":"jessica",},{"title":"rosh&quo ...

Need help figuring out how to use Javascript:void(0) to click a button in Selenium?

Struggling with finding the right solution, I have attempted various methods. Apologies for any formatting errors, but the element that requires clicking is: <button href="javascript:void(0)" id="payNewBeneficiary" class="button-new-payee"> ...

Continue duplicating image to stretch header across entire screen

Looking to create a seamless connection between a Header image (2300x328px) and another image (456x328px) so that the header fills the entire width available without overlapping due to a pattern. I need the second image to extend the header to th ...

Completing the regex properly

When using my editor, I am able to paste a video URL which is then converted by regex into an embed code. The URL in the WYSIWYG-editor looks like this: Once converted, the output HTML appears as: <p>http://emedia.is.ed.ac.uk:8080/JW/wsconfig.xml& ...

Attempted to create a node index.js file but encountered an error

Whenever I try to run express node.js on "localhost:3000", I keep getting an error message in my hyper terminal that says "unexpected token =". Here is the code snippet: //JS hint esversion:6 const = require("express"); const app = express(); app.get("/ ...

The webpage fails to return to its original position after the script has been executed

My website has a sticky div that stays at the top when scrolling down, but does not return to its original position when scrolling back up. Check out this example function fixDiv() { var $div = $("#navwrap"); if ($(window).scrollTop() > $div.data("top ...