In Javascript, when the Enter key is pressed for the first time, it should trigger a button click. However, when the Enter

Whenever the keyboard's enter key is pressed for the first time, it should trigger the button with id="botonCorregir". However, on the second press of the enter key, it should execute a function named url(). I have used a variable called cont to differentiate between the two actions in my JavaScript code. Despite my efforts, there seems to be an issue preventing it from working as intended.

Thank you!

Here is the relevant HTML:

<input id="respuestaUsuario"></input>

<button id="botonCorregir">Reply</button>
<a id="enlaceSiguiente" href="nextQuestion.html">Next question</a>

And the corresponding JavaScript:

<script>
var cont=0;
if(cont==0){
      // Should respond to the first press of enter
      var input = document.getElementById("respuestaUsuario"); 
    console.log('input: ', input)
    input.addEventListener("keyup", function(event) {
      if (event.keyCode == 13) {
       event.preventDefault();
       document.getElementById("botonCorregir").click();
      }
    });
    cont++;
}else{
      // Should respond to the second press of enter
    if (event.keyCode == 13) {
       event.preventDefault();
       document.getElementById("enlaceSiguiente").click();
      }
}
</script>

Answer №1

There are a few errors in your code that need fixing.

The issue lies in the way you assign events based on the variable cont. Once the value of cont is changed, JavaScript does not reevaluate the code. It only checks the condition once:

if(cont==0){}

A corrected solution would be:

var cont=0;
var input = document.getElementById('respuestaUsuario');

input.addEventListener('keyup', function (event) {
  event.preventDefault();
  if (event.keyCode == 13) {
    if(!cont){
      alert('one');
      document.getElementById("botonCorregir").click();
      cont++;
    }else{
      document.getElementById("enlaceSiguiente").click();
    }
  }
});

Answer №2

It seems like you were heading in the right direction, but the issue lies in the fact that your JavaScript code is only executed once. This means that the 'else' case will never be triggered. To address this, I have revised your code and implemented the check within the event listener:

        var cont = 0;

        var input = document.getElementById("respuestaUsuario");
        input.addEventListener("keyup", function (event) {
          if (event.keyCode == 13) {
            event.preventDefault();
            if (cont == 0) {
              cont++;

              document.getElementById("botonCorregir").click();
            } else {
              document.getElementById("enlaceSiguiente").click();
            }
          }
        });

I have also put together a CodePen for you to review.

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

Why don't updates made in the database reflect in real time?

Currently, I am diving into the world of Firestore's real-time functionality. Below is a snippet of my code where I am fetching data: useEffect(() => { let temp = []; db.collection("users") .doc(userId) .onSnapshot((docs) =&g ...

Incorporate jQuery to add numbering to rows along with input fields

I am trying to implement automatic numbering on the first column. Is there a way to increment the number by 1 every time the Submit button is pressed? jQuery: $(document).ready(function () { $("#btn-add").click(function () { va ...

Identifying the completion of loading a HTML page using an object tag

I am trying to load an HTML page using an object tag, and once the page is fully downloaded, I want to display something. I have attempted the following approach, but it is not working: document.querySelector(".obj_excel").addEventListener("load", funct ...

The flexslider isn't updating slides when clicking on thumbnails

Recently, I incorporated a CSS code to display an overlay when hovering over the thumbnails in my flexslider slideshow. However, after adding this code, I noticed that clicking on the thumbnail does not produce any action. .flex-control-nav li{ positi ...

The content inside a Textbox cannot be clicked on. I am seeking help with implementing JavaScript to enable it to be

As a newcomer in the world of programming, I am sharing a snippet of my JavaScript and HTML code with you. I am facing an issue where I want to enable users to start typing in a text box upon clicking on the text "User Name", without deleting any existing ...

What is the method for formatting within the <textarea> element?

While working on developing a comment system, I recently made the discovery that text areas cannot be formatted to retain paragraphs, line breaks, etc. This was particularly noticeable when comparing sites like StackOverflow, which uses a text editor inste ...

Submitting option values in AngularJS: A step-by-step guide

Why does AngularJS ng-options use label for value instead of just the value itself? Here is my current code: <select ng-model="gameDay" ng-options="gameDay for gameDay in gameDayOptions"> This currently displays: <select ng-model="gameDay" ng- ...

Is it possible to install a meteor package for only a specific platform?

Adding a single package called ground:db from https://github.com/GroundMeteor/db to my meteor project is something I'd like to do, but I only want it to be used in the cordova builds. It would be ideal if it didn't clutter up the assets on the we ...

What is the correct way to incorporate a for loop within a script tag in EJS?

When attempting to create a chart using chart.js, I encountered an issue. In order to retrieve my data, I attempted to use ejs tags. For example, within the ejs input HTML below, everything worked smoothly. <p>date: <%= today %></p> ...

What is the best way to fetch the title property from my Campaign Contract for displaying it in the render method?

I'm currently working on a unique crowdfunding DApp that requires constant access to contract variables through function calls for retrieval purposes. The getDeployedCampaigns function is responsible for returning an array of deployed campaign addres ...

typescript is failing to update CSSRule with the newly assigned background-color value

I am currently working on dynamically changing the CSS style (specifically background-color) for certain text on a webpage. To achieve this, I have been attempting to modify CSSRule by accessing the desired CSSRule based on selectedText. Here is the code s ...

Are there issues with the Ref when clicking on the IconButton from Material UI?

I'm currently using Material UI and encountering an error that I can't quite understand. The error pops up every time I try to click on the IconButton component to open a menu. The menu does display, but along with it, I receive this error messag ...

React App PWA ERROR: Service worker not registered to control the page and start_url

I am encountering an issue while building a progressive web app using Create React App. Lighthouse benchmarking results in an error, indicating that my PWA is not installable. Surprisingly, I face the same problem even when utilizing the official PWA templ ...

Utilizing Multer with Node.js to seamlessly handle photo uploads

Currently, I am trying to upload some photos to my server by referencing my friend's code. However, when I console log the "req" (console.log(req)), the output is different from what I expected. More specifically, when I try to access req.file, it ret ...

What is preventing me from being able to access a property within my function?

In the post method below, I am trying to access baseUrl. However, it is showing undefined. Can you help me understand why and provide a solution? const API = { baseUrl: "http://my_api_address", post: (path, payload) => { let headers = { ...

transferring background-image in html between elements

Imagine having a three-level hierarchy HTML code structured like this: <section> <div id="outer"> <div id="inner"> </div> </div> </section> If we set background-image:someImage.jpg to the section, and backg ...

Downloading a Facebook profile picture is a time-consuming task

I have a simple Christmas themed photo editing website that allows users to create holiday images. To achieve this, I require users to save their Facebook profile picture. However, the process is taking much longer than expected, usually between 15-30 seco ...

What are the steps for integrating mongoDB with an angular2 application?

I currently have my angular2 & mongoDB setup successfully. While I've managed to read JSON files using the HTTP service, my goal is to create a fully functional application with database connectivity as well. I'm seeking advice on how to con ...

Having trouble implementing a custom font family in a React Native Text component

Struggling to integrate a custom font into my react native app, I've gone through various solutions from SO and Google but nothing seems to work. I attempted to inform react native about the font by adding "rnpm": { "assets": [ "./assets/fonts/" ...

Node.js tutorial: Packing 2D boxes efficiently

Working on a web application using node js and in need of a box packing algorithm to determine the optimal solution. While I could attempt to create an algorithm from scratch (view http://en.wikipedia.org/wiki/Packing_problems), I'm curious if a simil ...