Keypress in JavaScript

Consider the function below:

function CheckInputType(Input) {
      inputType: Input
}

If a key is pressed, I want to cycle through different input values like this:

      window.addEventListener('keydown', e => {
        if (9 === e.keyCode) {
          e.preventDefault();
             CheckInputType(0)
//Switch from 0 to 1 when key is pressed again
             CheckInputType(1)
//Switch from 1 to 2 when key is pressed again
              CheckInputType(2)
//And so on
    }, false);

How can I achieve this functionality?

Answer №1

Here is a handy script to track keydown events with a counter.

let keyPressedCounter = 0;

window.addEventListener('keydown', event => {

  if (9 === event.keyCode) {
     
     event.preventDefault();
     keyPressedCounter++;
 
    
     if(keyPressedCounter % 3 == 0){
        RequestInputType(0)
     }
     else if(keyPressedCounter % 3 == 1){
        RequestInputType(1)
     }
     else if(keyPressedCounter % 3 == 2){
        RequestInputType(2)
     }
   }
},false)

Answer №2

Using a global variable to store the current argument for requestInputType() allows for easy incrementing and wrapping around after each call.

let currentArg = 0;
let maxArgs = 3;

window.addEventListener('keydown', event => {
  if (event.keyCode === 9) {
    event.preventDefault();
    requestInputType(currentArg);
    currentArg = (currentArg + 1) % maxArgs;
  }
}, 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

JavaScript's wildcard character, *, in a regular expression will always match something

I am currently attempting to verify whether a given string contains only uppercase letters, numbers, and underscores by utilizing the pattern matching approach with /[A-Z0-9_]*/. Despite this, executing the following code results in a return of true: /[A ...

AWS - lambda is unable to assume the defined role for the function due to restrictions

As a beginner with AWS CDK, I encountered an issue while setting up my Lambda function. Here is the code snippet: import { ManagedPolicy, Role, Group, User } from 'aws-cdk-lib/aws-iam'; import { NodejsFunction } from 'aws-cdk-lib/aws-lambda- ...

Deselect Certain Categories of Automatically Generated Tick Boxes

I have implemented some visually appealing "checkboxes" using li, span, and bootstrap glyphicon elements. These checkboxes display an active state when checked by adding the .active class. Upon activation of the active class, a hidden div beneath the boot ...

My components views are not being rendered in Angular 4

Currently, I am in the process of learning how to use Angular 4, but I seem to be encountering an issue. Despite having a functioning App template that renders perfectly fine, I am facing difficulties when attempting to render more than one template. I cre ...

Highlighting JavaScript code with React Syntax Highlighter exclusively

I've been struggling to highlight Ruby code, but it seems like no matter what I do, it keeps highlighting JavaScript instead. It's frustrating because I can't seem to get it right. import React from "react"; import atom from "node_module ...

organizing the div based on the given data

I'm working on developing a web application using HTML and AngularJS. There are two main div elements: Div 1 <div class="box1" style="margin-top:20px;"> <span ng-repeat="i in data" style="font-size:14px; font-weight:normal">{{i.div ...

Why is the jQuery Ajax AutoComplete feature not functioning properly?

Hey there, I'm currently utilizing CodeIgniter along with Ajax AutoComplete for jQuery in my project. When setting up my autocomplete feature in jQuery, I used the following code: a = $('.city').autocomplete({ serviceUrl: "<? echo $ ...

What steps can be taken to ensure that the application loading process is not reliant on web service

I recently developed a PhoneGap application that initiates a web service call upon loading the index.html page. The call is made using the following code: $.ajax({ type: "GET", url: "http://webserviceurl.com/service", cache: false, async: true, ...

Implementing Observable in NativeScript with TypeScript - A Step-by-Step Guide

Recently, I delved into the world of native-script framework and decided to dive into the "Get Started with JavaScript" tutorial provided on their official website. My background in Java has made me more comfortable with typescript, so I attempted to swap ...

Tips on removing previously selected files from a Bootstrap 4 input file

I am currently facing an issue with a form that includes an input file implemented using Bootstrap 4. The functionality of this input file depends on Javascript: when the user clicks on the "browse files" button, a window opens for file selection, and upon ...

In search of a tool that enables horizontal scrolling of content

I am on the lookout for a piece of Javascript code that can be integrated into my website to enable me to horizontally scroll content either from left to right or right to left. Although I found this script here: It offers the fundamental functionality th ...

Guide to personalizing the ngxDaterangepickerMd calendaring component

I need to customize the daterangepicker library using ngxDaterangepickerMd in order to separate the start date into its own input field from the end date. This way, I can make individual modifications to either the start date or end date without affectin ...

Order of callback execution in jQuery's ready function

When two JavaScript functions on a page need to be called once the document load is complete, is there a possibility that one function could be executed before the other, or will it always be the same order? For example, using jQuery with the following co ...

Dynamic jQuery backstretch feature: automatic image cycling and reversing

I am currently using backstretch on my website and attempting to create a continuous loop of the moving image by automatically shifting it from left to right and back. However, I am facing difficulties as the background only moves in one direction. I am se ...

Is it necessary to call detach() in rangy?

Utilizing the rangy library in my project and reviewing the documentation for detach: "Destroys the range when it is no longer to be used." I am encountering a dilemma as there isn't a suitable location for me to invoke detach in my code for certain ...

Dealing with infinite loop while verifying cookie in angularjs

In my client-side code, my goal is clear. If the user has the cookie, they are authenticated; otherwise, they are redirected to an authentication endpoint on the server. (function() { 'use strict'; angular .module('App', [ ...

Struggling with navigating through multiple pages in Python using Selenium? It seems like it's only able to retrieve information from either the

Currently exploring the world of web scraping with a main objective of extracting data and inserting it into a CSV file. Facing challenges specifically when dealing with scraping JavaScript on certain web pages. Despite attempting various strategies, I a ...

"Exploring the use of conditional rendering in React to dynamically hide and show components based

I am currently immersed in the world of React/Redux, focusing on an e-commerce project. This particular application offers two payment methods: cash and card payments. On the product display page, both payment icons are visible. However, I am seeking a sol ...

Utilize moment.js to format a datetime and display the corresponding timezone

I'm having trouble displaying timezones correctly using moment.js. I attempted to use the following code: var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z"); This returns something like: 08/05/2015 06:18 PM +02:00, which is okay, but I w ...

The use of jQuery.parseJSON is ineffective for a specific string

Why isn't jQuery.parseJSON working on this specific string? ({"stat":"OK","code":400,"data":[{"title":"Development Convention","event_type":false,"dates_and_times":[{"date":"28\/03\/2012","start_time":"10:00 AM","end_time":"10:00 AM"},{"dat ...