Is there a way to correlate keynum with an index number in an array?

In my array, the index numbers are set from 65 to 90 (a-z keycodes). I need to iterate through the array to check if the keynum generated from a keypress event matches one of the index numbers. If it does, I want to change the color of an onscreen button to red and display the corresponding String.fromCharCode in an element's innerHTML.

Assuming my button is like this...

<input type="button" id="a" value="A">

This is the JavaScript code...


document.onkeypress = keypress;

function keypress() {
    var buttons = [];
    var panel = document.getElementById("panel");
    var letter, i;

    for(i = 65; i <= 90; i++) {
        buttons[i] = document.getElementById(String.fromCharCode(i).toLowerCase());
    }

    var keynum = (window.event) ? event.keyCode: e.which;
    letter = String.fromCharCode(keynum);

    for(i = 65; i <= 90; i++) {
        if(buttons[i].id.toLowerCase().charCodeAt(0) === keynum) {
            buttons[i].style.backgroundColor = 'red';
            panel.innerHTML += letter;
        }
    }
}

Is there a way to make it so that when I press a button, the corresponding onscreen button changes to red? Here is a link to my JS Fiddle... http://jsfiddle.net/AdamMartin121/VXYFC/14/

Answer №1

function handleKeyPress() {


    var buttonMap = [];
    for (var idx = 65; idx <= 90; idx++) {
        buttonMap[idx] = buttonMap[idx + 32] = document.getElementById(String.fromCharCode(idx + 32));
    }

    var keyCodeValue = (window.event) ? event.keyCode : e.which;
    if (buttonMap[keyCodeValue]) {
        buttonMap[keyCodeValue].style.backgroundColor = 'blue';
    }
}

You were trying to compare buttonMap[idx] with keyCodeValue, but buttonMap[idx] holds a DOM element, not a number. It looks like you just need to use keyCodeValue as the index in the buttonMap array.

I made adjustments to the buttonMap array so that it covers both uppercase and lowercase letters, using a loop to populate it. Initially, only uppercase letters were included, requiring the Shift key to trigger any actions.

FIDDLE

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

jQuery outputs an empty array

SITUATION When jQuery does not find any matching elements based on the specified selectors, it returns an empty array []. SUMMARY OF RESULTS var a = $(""); // -> returns [] var b = $(); // -> returns [] var c = $(null); // -> ret ...

Is it possible to assign variables inside an http call from a function in AngularJS?

Seeking urgent assistance. I need help with a function that resembles the following: $scope.getData = function(id) { $http.get('/url' + id).success(function (data) { return data.a.b.c; }); }; In another function, I have the fol ...

Choose several locations recommended by Google Places

Looking to implement a multiple select feature on v-select to allow users to select one or more cities suggested by Google. Has anyone successfully done this before? I haven't been able to find any examples. https://vue-select.org/ ...

Enhance your MUI treeview by incorporating stylish connecting borders

I've been trying to add borders that connect to the nodes in the mui treeview, but I'm having difficulty with not having a vertical border when it's the last leaf node. It currently looks like this: See border example here. However, it sh ...

What is the best method for converting IDs into objects within ng-options in Angular?

Is there a way to dynamically use an array of IDs as the source of my ng-option directive inside of select? Instead of creating an array of objects with corresponding IDs, I am wondering if there is a method to set a function as the source of ng-option. ...

Adjusting the maximum value in the Angular Bootstrap UI rating system using ng-model

I have implemented a rating system using Angular-UI. The number of stars displayed is determined by a variable named max. While I am able to display this variable within an input field using ng-model, any modifications made to it do not reflect in the numb ...

Is there a way to asynchronously load image src URLs in Vue.js?

Why is the image URL printing in console but not rendering to src attribute? Is there a way to achieve this using async and await in Vue.js? <div v-for="(data, key) in imgURL" :key="key"> <img :src= "fetchImage(data)" /> </div> The i ...

Stylish CSS Tricks with Font Awesome Icons

In my project, I am utilizing Font Awesome SVG with JavaScript multiple times. Currently, I am working on creating a button that displays an arrow icon to the right of the text when hovered over. However, I encountered an issue where there is a blank squar ...

Utilizing useEffect to dynamically update the state in useReducer

Currently in my application, I am integrating React Hooks/Context API. The task at hand is to transfer data fetched from localStorage and assign it to initialState.carts or state.carts when the Provider component mounts. However, there seems to be a limita ...

JavaScript: A dynamic table is created with columns populated by JSON data. The row structure is compromised

On my webpage, I pull in two sets of JSON data: 1) warehouses and 2) items. After receiving an Ajax search response from my view, I need to dynamically generate the TDs of a table based on the warehouses information. The goal is to populate all TDs for ev ...

Select an option from a dropdown menu using Jquery depending on the previous selection made

Can data be retrieved from the database based on the selection made in a drop-down menu? For instance: <select id="paramscountries" class="chzn-done" style="display: none;" name="params[countries][]" multiple="true" size="10"> <option value= ...

Ways to display a variable within an HTML element

What could be causing variable a to be undefined? export default function Surah() { let a; const updateVariable = (id) => { a = id; console.log(a); }; return ( <div> <div> <button onClick={() => ...

Header vanishes while using a JavaScript function to search through an HTML table

I'm facing an issue with a search function in a php script. The search function, written in javascript, is designed to sift through the table below and extract matching content as the user inputs text into the search field. It looks specifically withi ...

The form will be submitted even if the validation conditions are not met, and the form

I've been struggling to understand why this issue keeps occurring despite hours of unsuccessful research. Here's the code for a registration page that submits the form regardless of the conditions being true or false. I've experimented with ...

Printing the result of an SQL query in Node.js without using braces

As a beginner in node.js with only a basic understanding of javascript, I apologize if I make any mistakes. I attempted to display the results retrieved by an SQL query in node.js using: <p>Users are " + util.inspect(results) + ".</p>" an ...

Having trouble incorporating a react component I discovered into my application. Encountering an error message stating "Attempted import error."

My aim is to integrate an existing react component (shown below) that I came across on the internet into my application for use, specifically an animated navigation bar. Upon attempting to compile the code snippets below (snippets 2 and 3), I encountered ...

Code functioning correctly in Chrome but encountering issues in Firefox

I've come across an issue with my HTML and JavaScript code for a select drop-down box. My goal is to have the background color of the selected option update to match the color selected by the user. Currently, when using Firefox, the hover color chang ...

Unable to find the solution for 'material-ui/Button'

I recently encountered an issue while trying to integrate the material-ui library into my existing React project. I used the command npm install --save material-ui, but it resulted in an error upon running it. The error message received is as follows: ...

What is the reason that the select option change event does not allow the use of "this" and event.target to access the selected value

Why is it difficult to obtain the selected value in a select option change event using this or event.target, and instead needing to use cumbersome code like $( "select option:selected" )? This issue arose when I needed to access certain data-* attributes ...

When attempting to send coordinates to the Polyline component in React Native, an error is encountered stating that NSNumber cannot be converted to

Trying to pass coordinates from BackgroundGeolocation.getLocations() is causing an issue. Upon passing the coordinates, I encounter the following error message: JSON value '-122.02235491' of type NSNumber cannot be converted to NSDictionary I ha ...