Challenge with the submission event listener

I am struggling to create my first event listener for the submit button that should respond to both a click and an enter key press. Currently, it is not working for either event, and I am unsure why. I do not intend to send any data to another page; I simply want it to trigger other actions.

var domStrings = {
    submit: document.querySelector('#submit')
}
var checker = function() {
    var lcase;
    domStrings.submit.addEventListener("click", function(e) {
        e.preventDefault();
        console.log('form submitted');
        lCase = guess.value.toLowerCase();
        turnCounter++;
        if (entryField.value.includes(lCase)) {
            for (i = 0; i < entryField.value.length; i++) {
                if (lCase === entryField.value[i]) {
                    retainAndReplace(domStrings.word.textContent, i, lCase)
                }
            }
        } else {
            //tell user they're wrong
            wrong.style.visibility = 'visible';
            wrong.classList.add('.fade-out-wrong')
            setTimeout(invisibleWrong, 4000);
            guessCounter--;
            if (guessCounter < 1) {
                //display game over
                over.style.display = 'inline'
                chances.textContent = `Guesses remaining: 0`;
                wrong.style.display = 'none';
                //hide dashes
                word.style.display = 'none'
            } else {
                chances.textContent = `Guesses remaining: ${guessCounter}`;
            }
        }
    })
}
checker()
<input type = 'text' id = 'guess' placeholder = 'Letter Guess' maxlength = '1'>
<button type = 'submit' id ='submit'> Submit </button>

Answer №1

When the submit event occurs, it is triggered on the actual <form> element and not on any buttons within it. To solve this, you must encapsulate your elements within a <form> tag and then add the event listener to that form.

form.addEventListener("submit", event => {
  event.preventDefault()
  output.innerHTML = guess.value
})
<form id="form">
  <input id="guess" placeholder="Letter Guess" maxlength="1">
  <button type="submit">Submit</button>
</form>
<div>Guessed letter: <span id="output"><span></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

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

Steps to gather all the images within a directory

Take a look at this demo When you click on the "next" button, new images are loaded from the internet. In my application, all the images are stored in the img/image folder with names like 1.jpg, hi.png, etc. My question is, how can I display these image ...

Check if a Discord.js bot responds based on whether a user holds a designated role

I'm looking to make my bot respond to a specific role. If the user does not have that role, I want the bot to reply with a message saying "You are not allowed to perform this command." Here is the code snippet I am using: client.on("message", (message ...

Unable to assign a boolean value to a data attribute using jQuery

I have a button on my page that has a special data attribute associated with it: <button id="manageEditContract" type="button" class="btn btn-default" data-is-allow-to-edit="@(Model.Contract.IsAllowToEdit)"> @(Model.Contract.IsAllowToEdit ? " ...

I can't find my unit test in the Test Explorer

I'm currently working on configuring a unit test in Typescript using tsUnit. To ensure that everything is set up correctly, I've created a simple test. However, whenever I try to run all tests in Test Explorer, no results are displayed! It appear ...

Using Special Characters in React JS Applications

When handling CSV uploads with accented characters such as émily or ástha, I encountered the need to encode and pass them to the backend. Experimenting with different approaches, I tried adjusting the file type in FormData from 'text/plain' to ...

Storing multilingual JSON data in AngularJS for faster access

I have successfully implemented a multi-language concept in my application, but I am facing an issue where the language (.json) file is being loaded for every field. As a result, the application takes a longer time to load. My requirement is to load the .j ...

How can I make Material UI's grid spacing function properly in React?

I've been utilizing Material UI's Grid for my layout design. While the columns and rows are functioning properly, I've encountered an issue with the spacing attribute not working as expected. To import Grid, I have used the following code: ...

Vows, Tobi, and Node.js come together for comprehensive REST API testing

Currently, I am in the process of merging the examples here and here to create a vows test for my node.js / express application that does the following: Creates a new user object Verifies that the response is correct Utilizes the returned _id to perform ...

Can two writable stores in Svelte be set up to subscribe to each other simultaneously?

There is a unique scenario where two objects share data, yet have different structures. For instance, the 'Team' object has the team ID as its key. The 'Team' object includes 'name' and 'users' objects as its values ...

Creating a JSON data array for Highcharts visualization: rearranging values for xAxis and columns

I am facing an issue with my column chart where JSON data is being parsed in the "normal" form: Years are displayed on the xAxis and values on the yAxis (check out the fiddle here): array( array( "name" => "Bangladesh", ...

What causes the issue when attempting to import multiple CSS files in a Vue.js project using @import more than once?

Currently, I am working on a project that involves one main component and several child components. These components require custom CSS files as well as additional vendor CSS files. A challenge I encountered is that I cannot use the @import "path/to/css/fi ...

Utilizing NextJs req.query parameter in Prisma for advanced query filtering

Currently, I am delving into the world of NextJS and experimenting with sending requests to an API while passing a parameter that is then used by Prisma to query the database. In order to achieve this, I've created a new file located at /api/posts/[s ...

Protecting an API with passport-local authentication

Let me get right to the point. I've developed a secure application using passport-local, with all routes well-covered. The purpose of my app is to retrieve data from MongoDB and serve it as an API that feeds into d3 charts. While all my webpages are s ...

What is the most efficient way to send multiple arrays by selecting checkboxes?

Currently, I am faced with a challenge where I have a selection of items from a list that need to be submitted in the form of three different arrays with distinct values to PHP. These arrays include: Device id, Client comment, and Manufacturer comment. < ...

Is it possible to run npm scripts directly?

There is a script in my package.json file "start": "cross-env NODE_ENV=development PORT=3000 CODE_SPLIT=0 node ./react-imvc/bin/www-babel-register", I need to run the script with the --inspect flag, but I am unable to modify the package.json. I would lik ...

Continue looping in Javascript until an empty array is identified

Currently, I am in search of a solution to create a loop in Javascript that continues until the array of objects is empty. The object I am working with looks like this: "chain": { "evolves_to": [{ "evolves_to": [{ ...

Service for Posting in Angular

I am looking to enhance my HTTP POST request by using a service that can access data from my PHP API. One challenge I am facing is figuring out how to incorporate user input data into the services' functionality. Take a look at the following code snip ...

The 'BaseResponse<IavailableParameters[]>' type does not contain the properties 'length', 'pop', etc, which are expected to be present in the 'IavailableParameters[]' type

After making a get call to my API and receiving a list of objects, I save that data to a property in my DataService for use across components. Here is the code snippet from my component that calls the service: getAvailableParameters() { this.verifi ...

Customize the icon used for expanding and collapsing in AngularJS

I want to modify the icon (e.g., plus, minus) when clicking on an expand-collapse accordion. Currently, I am using the Font Awesome class for icons. While I know it can be easily achieved with jQuery, I'm wondering if there is a way to do this in Angu ...