Using Javascript to trigger form submission using arrow keys

There are four forms displayed on a single page, and I want each form to be submitted based on the arrow key that is pressed.

<form  name='go_north' action='' method='post'>
<input type='hidden' name='direction' value='north' />
</form>

<form  name='go_east' action='' method='post'>
<input type='hidden' name='direction' value='east' />
</form>

etc...

I understand how to achieve this with text inputs that have focus, but I am struggling to implement it with hidden inputs. Additionally, it should only work in Chrome. Any suggestions or advice on how to tackle this issue would be highly appreciated.

Answer №1

Implement a

document.addEventListener("keydown", function(){})
to detect key presses, then identify the keycode and use it to submit a form based on the pressed key.

You can easily submit forms by selecting the form and invoking .submit() on it!

document.addEventListener("keydown", function(event) {
  var code;
  if (event.key !== undefined) {
    code = event.key;
  } else if (event.keyIdentifier !== undefined) {
    code = event.keyIdentifier;
  } else if (event.keyCode !== undefined) {
    code = event.keyCode;
  }
  console.log(code);
  handleArrow(code);
});

function handleArrow(code) {
  switch (code) {
    case 'ArrowLeft':
      submitForm('go_west');
      break;
    case 'ArrowRight':
      submitForm('go_east');
      break;
    case 'ArrowDown':
      submitForm('go_south');
      break;
    case 'ArrowUp':
      submitForm('go_north');
      break;
  }
}

function submitForm(id) {
  $("#" + id).submit();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="go_north">
  <label for="north">north</label>
  <input id="north" type="text" name="north" value="north">
</form>
<form id="go_east">
  <label for="east">east</label>
  <input id="east" type="text" name="east" value="east">
</form>
<form id="go_south">
  <label for="south">south</label>
  <input id="south" type="text" name="south" value="south">
</form>
<form id="go_west">
  <label for="west">west</label>
  <input id="west" type="text" name="west" value="west">
</form>

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

Guide to removing selected value from a combobox in Angular

I am working on a simple HTML file that consists of one combobox and one clear button. I want the clear button to remove the selected value from the combobox when clicked. Below is my code: mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayou ...

I am facing an issue with Angular where the $http.get method is

It seems like there must be a small oversight causing this apparently simple problem. I have a function that interacts with the Spotify API to search for an artist. I know that by accessing the corresponding route using a standard URL, a result is returne ...

How to manipulate iframe elements using jQuery or JavaScript

Hey there, I have a simple task at hand: I have a webpage running in an iFrame (located in the same folder on my local machine - no need to run it from a server) I am looking to use JavaScript to access elements within this iFrame from the main page. How ...

Displaying and hiding the Angular <object> element

I am faced with a challenge involving managing files of various formats and creating a gallery with preview functionality. Everything works smoothly when clicking through items of the same format, like JPEGs. However, an issue arises when switching from vi ...

Problem: Implementing a horizontal scrolling feature using Skrollr

I'm interested in creating a horizontal animation controlled by skrollr. As I scroll down, I want the elements on my page to move from left to right within my container. When all elements have the same width, setting the scrolling data from 100% to 0 ...

Using Typescript to mute audio elements within HTML documents

I have a scenario where I want to mute audio that automatically plays when the screen loads. In order to achieve this, I am attempting to add a button that can toggle the audio mute functionality using Typescript within an Angular4 application. The code sn ...

authorization for certain express routes using passport.js

Securing certain express routes with Passport.js authentication Steps for authenticating specific routes in Passport.js Looking for a method to authenticate particular routes using Passport.js Your assistance is greatly appreciated... ...

Which approach is more impactful: consistently sending an ajax request or breaking down the result within a function?

My JSON data consists of news entries with titles, text, and dates. Here is an example: { "news": [ {"title": "some title #1","text": "text","date": "27.12.15 23:45"}, {"title": "some title #2","text": "text","date": "26.12.15 22:35"}, ... ...

Avoid unnecessary re-renders in React Redux by ensuring that components do not update when properties are not utilized in their

I'm encountering an issue with a component that keeps re-rendering. I've implemented Redux to handle my states. Within a component, I access a property (isPlaying: bool) from the state using mapStateToProps in various methods of the component, ex ...

The function designed to create in-line TailwindCSS classNames may work inconsistently in React and NextJS environments

Currently, I am utilizing TailwindCSS to style a web application. One frustrating aspect is that when attempting to add before: and after: pseudo-elements, it must be done individually. For instance, take the navigation drop-down button styling: <span ...

Including variables in package.jsonORInjecting variables into package

I'm currently developing a React application and I am trying to figure out how to pass a variable from the .env file into package.json: {"proxy": "ENV_VAR"} Is there a way to achieve this? In addition, our app is built using Docker. Is it possible ...

Determining the total number of combinations possible from a collection of five arrays containing items

I have five massive collections filled with various strings, and each of them contains a different number of elements. Below are examples of the lists: List 1 "Jeffrey the Great", "Bean-man", "Joe", "Charles", "Flamur", "Leka", ...

Obtaining the initial value from an Observable in Angular 8+

Initially, I have a page form with preset values and buttons for navigating to the next or previous items. Upon initialization in ngOnInit, an observable provides me with a list of 3 items as the starting value - sometimes it may even contain 4 items. Ho ...

A guide to loading CSS and JavaScript files asynchronously

Is it possible to use loadCSS (https://github.com/filamentgroup/loadCSS/blob/master/README.md) to allow the browser to asynchronously load CSS and JavaScript? This is what I currently have in my head tag: <link rel="preload" href="http://zoidstudios. ...

Tips for modifying the properties of variables within an array using JavaScript

I have an array that holds variables used to control a specific template. divisionsListToManipulate: ['showActivitiesSection', 'hideAssignActionplanDiv', 'displayProp ...

Adjust the opacity of a div's background without impacting the children elements

I am currently working on a dynamic content display in my HTML page using some knockout code. The setup looks like this: <section id="picturesSection" class="background-image" data-bind="foreach: { data: people, as: 'person'}"> <div ...

Encountering an error stating that 'coordinates should consist of an array with two or more positions'

Utilizing turf.js to generate a line depicting the path of an individual while their location is tracked. An array of coordinate arrays resembling Turf.js (lineString) is causing this error: Uncaught Error: coordinates must be an array of two or more posi ...

Developing a dynamic row that automatically scrolls horizontally

What is the best method for creating a div box containing content that automatically slides to the next one, as shown by the arrows in the picture? I know I may need jquery for this, but I'm curious if there's an alternative approach. oi62.tinyp ...

Encountering a 404 error while accessing my meticulously crafted express server

After ensuring that the server is correctly set up and without any errors related to imports or missing libraries, I utilized cors for development purposes. A 404 error persisted even after attempting to comment out the bodyparser. https://i.stack.imgur.c ...

What is the method for defining functions that accept two different object types in Typescript?

After encountering the same issue multiple times, I've decided it's time to address it: How can functions that accept two different object types be defined in Typescript? I've referred to https://www.typescriptlang.org/docs/handbook/unions ...