Achieve a new line break when the user hits the "Enter" key using HTML and JavaScript

I'm in the process of developing a Chrome Extension that allows users to create a to-do list. My goal is to enable users to submit their task by pressing the "Enter" key, which should move the task to the next line after submission. I am currently facing challenges with implementing this functionality.

HTML:

<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
  <li>test</li>
</ul>

Javascript:

$(() => {
   $('#newtask').on('keydown', (e) => {
     if(e.keyCode == 13){
       ???
     }
   });
 });

Answer №1

Make sure to attach the keypress eventlistener to the input element, not the ul. When the enter key is pressed, take the content of the input field, create a new li element, set its text to the entered value, append it to the ul, and then clear the input field.

$(() => {
  $('input').on('keypress', function(e) {
    if (e.keyCode == 13) {
      const newTask = $(this).val();
      if (newTask) {
        $('#tasksUL').append(`<li>${newTask}</li>`);
        $(this).val("");
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
  <li>test</li>
</ul>

Answer №2

To implement this functionality using vanilla JavaScript, you simply need to attach an eventListener to the input element itself that listens for keydown events.

let taskList = document.getElementById('tasksUL');
document.getElementById('newTask').addEventListener('keydown', (e) => {
    if(e.key == 'Enter'){
        let newItem = document.createElement('li');
        newItem.innerText = e.target.value;
        taskList.appendChild(newItem);
    }
});

Answer №3

If you need the list to display the text input by the user, consider using the jQuery append method for this purpose.

$('#newtask').keydown(function(e){
    if (e.which == 13) {
        //Create new HTML element to append:
        var newLi = "&lt;li&gt;" + $('#newtask').val() + "&lt;/li&gt;";
        $('#tasksUL').append(newLi);
    }
});

You can test out my implementation on JS Fiddle

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

Storing video blobs in the filesystem using Electron and Node.js

My electron application allows users to record video from their webcam using the MediaRecorder API. After hitting the "stop record" button, I am able to obtain a blob of the recorded video. I am trying to figure out how to convert this blob into a real w ...

passport not initializing session with requests

I am currently utilizing passportJS for managing login and persistent sessions on the server backend. While everything functions properly when sending requests from the server frontend (a webpage that I didn't create and lack sufficient knowledge to ...

Issue with TableHead not functioning properly when sorting is requested

I'm currently facing an issue with my table that has clickable row headers for sorting functionality using the onRequestSort function. Unfortunately, it seems like this feature is not working as expected. I have implemented the sorting logic using rea ...

Issue: The module 'xdl' cannot be located while executing the command "npm start" in React Native

Recently, I delved into learning React Native through an online Udemy course. Everything was going smoothly until a few days back when I encountered an error message after running the simple "npm start" command. Despite trying various solutions like reinst ...

Tips for CSS and jQuery: Show link when hovered over and switch the visibility of a content div

I'm facing an issue with a link in the horizontal navigation bar. When a user hovers over it, I want another div to slide down just below it. The problem is that using the .toggle method doesn't work as expected. It continuously toggles the div e ...

i am trying to execute a function in an angularjs controller through html, but the scope variable that i am

Being new to angularjs, I'm looking to understand the process of calling a function defined in a controller from HTML within angularjs. I have written the following code in my HTML: First.html <input type="text" ng-model="model.name" name="name ...

What is the process for inserting text or letters into a checkbox using Material Ui?

I am looking to create circular check boxes with text inside them similar to the image provided. Any help or guidance on achieving this would be greatly appreciated. View the image here ...

A guide to removing functions from the render method

Greetings! Currently, I am in the process of creating a simple webpage that utilizes a map function to display all details to the user. Some fellow developers have advised me to remove my functions from the render method, as it continuously renders unneces ...

When the JavaFX ComboBox drop-down opens in an upwards direction, the border appears incorrectly

While working with Java 8, I encountered an issue with the "javafx.scene.control.ComboBox" where if it doesn't have enough room below, it pops up instead. Strangely, the border styling of the elements still behaves as if it should pop down. Is there ...

Mishandling of string interpretation

I'm having trouble converting ANSI color codes from console output into HTML. While I discovered a script that can handle this task, I am struggling to make it parse the strings within node js properly. Even when I attempted to JSON.stringify it to in ...

Can a direct link to a Redis server be established through a web browser?

Can a connection be established with a redis server directly from the browser? In node, you can create a TCP connection using var client = net.connect(port, host);. I'm curious if it's possible to achieve the same in the browser either through Br ...

Tips for designing a navbar specific to a profile section

I am currently working on an angular application with a navigation bar composed of anchor tags. When the user logs in, I have an ngIf directive to display my profile icon with dropdown options. However, I am facing challenges in styling it correctly. I aim ...

I require the ability to access a reference parameter with a dynamically changing name within a Vue template

<div v-for="x in 4" :class="(images[x] === null) ? 'not-removable' : 'removable'" class="img-container"> <input style="display: none" type="file" ...

Automatically adjust CSS grid to fill based on the width of child elements

Can a CSS grid adjust its widths dynamically based on the content of its children? I believe not, but I wanted to confirm. I attempted this approach without success. const Grid = styled.div` display: grid; grid-auto-flow: row; grid-template-columns ...

The location layer on my Google Maps is not appearing

For a school project, I am working on developing a mobile-first website prototype that includes Google Maps integration. I have successfully added a ground overlay using this image, but I am facing issues with enabling the "my location layer". When I tried ...

Combining the total of numerous inputs that are multiplied by a specific value all at once

Hey, I've been working on a project with a table and an input field with costs using jQuery. You can check out This Fiddle for reference. $( ".total" ).change(function() { let i = 1; var input001 = document.getElementsByName(i)[0]; var ...

Vue.js - I am looking to create dynamic buttons that change color when clicked

I have dynamically created buttons using v-for and now I want the clicked button to change color while the others remain the same. <template> <div id="exam-screen" class="exam jumbotron"> <h1>{{ title }}</h1> <div cl ...

Leaflet setStyle changes are effective when applied through the console but do not reflect in the actual

I currently have a map with around 1000 polygons that I am loading onto it. My goal is to color these polygons based on a specific property value. The code snippet below showcases my approach, but the results are not as expected. mapLayerFieldGrid = new L ...

The closing brackets in PHP substr() function are causing style issues

Here's the scenario: I entered a large amount of content in a text editor (WordPress). Now, I want to display this content on my homepage using PHP queries. In order to limit the content size to 100-200 characters, I used the substr() function i ...

A guide on effectively utilizing ref forwarding in compound component typing

I am currently working on customizing the tab components in Chakra-ui. As per their documentation, it needs to be enclosed within React.forwardRef because they utilize cloneElement to internally pass state. However, TypeScript is throwing an error: [tsserv ...