When the enter key is pressed by the user, execute the equivalent of clicking the submit button using JavaScript

Is there a way to make the enter key perform the same action as my submit button?

I've been struggling with getting my form to submit when the user presses either the submit button or the enter key on the keyboard.

I've experimented with using if statements and keycode 13, but so far nothing has worked for me.

Below is the Javascript code I've been working with:

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

    // Add event listeners
    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(event) {
        console.log('=' + event.target.className);
        if(event.target.className.indexOf('todo-item') < 0) {
            return;
        }
        console.log(event.target.className.indexOf('completed'));
        if(event.target.className.indexOf('completed') > -1) {
            console.log(' ' + event.target.className);
            event.target.className = event.target.className.replace(' completed', '');
            document.getElementById('add-item').value='';
        } else {
            console.log('-' + event.target.className);
            event.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'));
        document.getElementById('new-item-text').value = "";
    }

    function removeItem(event) {
        if(event.target.className.indexOf('remove') < 0) {
            return;
        }
        var el = event.target.parentNode;
        el.parentNode.removeChild(el);
    }

    function changeTitle() {
        var title = prompt("change the title");
    }

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

});

Answer №1

To achieve this functionality, you need to implement the keydown event as demonstrated in the code snippet below:

document.onkeydown = function(evt) {
    var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
    if(keyCode === 13) {
         // Insert your function call here
    }
}

Answer №2

To enhance your event listener collection, consider including the following code snippet:

document.getElementById('add-item').addEventListener('keydown', handle, 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

Tips on adding a base64 encoded image string to a JSON object using JavaScript

I'm trying to convert an image file into a JSON object using JavaScript. I've managed to turn the image into a string by utilizing base64 encoding, but I'm unsure how to then convert this string into a JSON object. Can anyone help? ...

Organizing Information with React Redux

I am currently working on implementing a sort button for my data (menus) to have them sorted alphabetically. I have already added the necessary code to sort menus in my main container, but now I'm wondering what would be the most straightforward way t ...

Flask application experiencing issues with loading CKEditor

Currently, I am working in PyCharm to develop a basic web application. My goal is to use CKEditor to allow for customization of certain form elements. To provide some context, here is the complete directory structure: <Root> -<app> -< ...

Filtering Tables with AngularJS

Currently, I'm experimenting with using angularJS to filter data in a table. My goal is to load the data from a JSON file that has a structure like this (example file): [{name: "Moroni", age: 50}, {name: "Tiancum", age: 43}, { ...

How can I preserve the backslashes when passing a file path from a child window to an opener in asp.net?

I attempted to transfer a string value from a child window to the text box in an open window. The specific value is: string fileName = @"C:\aaa.txt"; After sending the above value to the parent window, the backslash \ disappears automatically, ...

When trying to open an HTML table that was exported to .xls file using FireFox for downloading, it fails

I have been utilizing a function that was sourced from stackoverflow. It functions correctly on Internet Explorer and Google Chrome, however, on FireFox, the downloaded file cannot be opened in Excel. When attempting to open the file in Excel, it shows up ...

Convenient way for users to easily choose an icon from a vast selection of icons

I am currently working on a web application that allows users to create new categories. These categories are then inserted into a database using form post. Each category should have an icon associated with it, and I want users to be able to select the ico ...

Personalize headers in v-data-table while preserving default sorting capabilities

I'm looking to enhance my v-data-table by making the table headers "tab-able". To achieve this, I decided to create a slot and include tabindex on the columns. However, I encountered an issue where the sorting functionality stopped working. Does an ...

Paste the formatted text from clipboard into the body of a react mailto link

I have a requirement for users to easily send a table via email by copying and pasting it into the subject line. You can view a live demo of this feature on CodeSandbox: copy and paste rich text Below is the function that allows users to copy and paste ri ...

Is Selenium suitable for testing single page JavaScript applications?

As a newcomer to UI testing, I'm wondering if Selenium is capable of handling UI testing for single-page JavaScript applications. These apps involve async AJAX/Web Socket requests and have already been tested on the service end points, but now I need ...

How can we display a placeholder while hovering over a text input field

When hovering over the textbox, I'd like the placeholder to become visible. <input type="text" placeholder="please input your name"/> ...

Accessing the current clicked item in $scope using an Angular Directive within ng-repeat

I have set up a custom directive called calendar which includes a date picker created in JQuery. To associate the ng-model with the date picker, I am using the following code successfully: var clickedID = "#" + $scope.indexid + "_datePicker"; $(clickedID ...

Understand which form has been submitted

I have eight Forms in a page (Form0, Form1, Form2 and so forth). Each form, when submitted, sends data to ReassignPreg.php using JavaScript, which then searches for the data in the database and returns it as JSON. The corresponding divs on the page are the ...

Is the method .hide("slow") performed synchronously or asynchronously?

When it comes to the $.ajax() method, we are aware that it is asynchronous. This means that the next statement begins executing before the ajax() method is fully completed. The 'ajax()' method continues to run concurrently with other tasks. On th ...

Running complex operations within a sorting function just once

I am facing the challenge of sorting an array of objects based on multiple date fields, with the added complexity of excluding certain dates depending on the category. In order to optimize performance, I want to minimize the number of times the getUsefulJo ...

Is it possible to update a statement if autocommit is turned off?

If I have code similar to the following: let connection; let preparedStatement; connection = createConnectionSomehow(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(query1); preparedStatement.executeUpdate(); prepared ...

Add a document to MongoDB and then tailor the data using a separate query before insertion

My request is quite simple: I need to add a new document to my MongoDB database. However, before doing so, I must first check if the slug already exists in the database. If it does, I need to rename the slug before proceeding with the insertion. I have b ...

Error: The property 'fixtures' of an undefined object cannot be accessed. This issue arose from trying to access nested JSON data after making

Struggling with asynchronous calls, JS, or React? Here's my current challenge... Currently, I am using the fetch library to display a table based on data structured like this (note that there are multiple fixtures within the fixtures array): { " ...

"Implement a feature in React.js to dynamically hide an element towards the center

I'm attempting to center align my element, similar to this example here. I'm working with react.js and for some reason, the jQuery code provided is not functioning as expected. $('#img-funder-logo').hide('scale', { percent: 0 ...

Using XSL variables in JavaScript code

I've noticed that there have been similar questions asked, but none of the solutions seem to help in my case. So, I have this variable named 'var': <xsl:variable name="var"> val </xsl:variable> Now, I want to use it like thi ...