Choosing from a range of triggers and extracting information from an object

I'm in the process of developing a user-friendly method for selecting the trigger key that activates the code. This is what I have so far.

var triggers = {space:"32",enter:"13",tab:"9"};
var triggerKeys = ["space","enter"];

$('input').on('keypress',function(event) {
 var unicode= event.keyCode ? event.keyCode : event.which;
   if(unicode === triggers[triggerKeys]) {
       //code initiation here
   }

However, this current setup isn't functioning as intended. Any suggestions on how I can modify it so that the code is activated when any of the keys in the triggerKeys array are pressed, especially if there are multiple trigger keys?

Currently, the code only works for one trigger key. Should I use a loop to accommodate multiple trigger keys?

Answer №1

Unsure of your specific inquiry, but a possible solution could involve the following approach :

$('input').on('keypress',function(e) {
    switch (e.which) {
        case 32: //space
            console.log('space');
            break;
        case 13: //enter
            console.log('enter');
            break;
        case 9: //tab
            console.log('tab');
    }
});

It appears using an array as a key for another array has posed challenges in my experience?

If you simply want to verify if a key exists in an array, consider storing the keycodes :

var triggerKeys = [32, 13, 9];

$('input').on('keypress',function(e) {
    if ( $.inArray(e.which, triggerKeys) != -1 ) {
       // one of the triggerkeys was pressed
    }
});

MODIFICATION:

Below is an alternative example utilizing the map you're employing, and validating if a trigger key was pressed :

var triggerKeys = ["space","enter", "tab"];
var triggers    = {space: 32, enter: 13, tab: 9};

$('input').on('keypress',function(e) {
    var arr = $.map(triggerKeys, function(el, i) {return triggers[el];});
    if ( $.inArray( e.which, arr ) != -1 ) {
        console.log('trigger key pressed')
    }
});

FIDDLE

Answer №2

If you need to execute certain code based on the value of the variable unicode, one way is to check for the presence of that value in a set.

An easy method is to use an array to create your set:

var triggerKeys = [32, 13];

You can then check like this:

if (triggerKeys.indexOf(unicode) >= 0) {
    // ...
}

However, keep in mind that not all browsers may support indexOf. As an alternative, you can simulate a set using:

var triggerKeys = {32: true, 13: true};

and then simply do:

if (unicode in triggerKeys) {
    // ...
}

UPDATE

To make your code more readable, you can define key names and key codes as follows:

var triggers = {space: 32, enter: 13, tab: 9};
var triggerKeys = ["space", "enter"];

The actual trigger key codes can be computed from the triggers object:

var triggers = {space:"32",enter:"13",tab:"9"};
var triggerKeys = ["space", "enter"];
var triggerKeyCodes = {};

for (var i = 0; i < triggerKeys.length; i += 1) {
    triggerKeyCodes[triggers[triggerKeys[i]]] = true;
}

This will result in the triggerKeyCodes object looking like {32:true, 13:true}. You can then check like this:

if (unicode in triggerKeyCodes) {
    // ...
}

View demo here: http://jsbin.com/eqoyag/5/edit

Considering you are already using jQuery, adeneo's solution might be more efficient. The future versions of JavaScript promise cleaner alternatives with features such as comprehensions and maps.

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

PHP script not being triggered by Ajax upload

After identifying and fixing errors through the Chrome console log, I am facing a new issue where the PHP script responsible for processing the data is not being called. <legend><strong>Choose a machine model</strong></legend> < ...

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

Breaking the Boundaries of Fuzzy Search with JavaScript

I am currently utilizing ListJS's plugin for fuzzy search. It can be found at the following link: In an attempt to enhance the plugin, I implemented my own method to filter by the first letter of the items in the list. This involved selecting from an ...

Activate menu on click

I need help creating a smooth transition effect for opening and closing a menu on my one-page website. I have some JavaScript code to control the menu visibility, but it currently appears abruptly without any transition effects. Is there a way to add a fa ...

Interdependent function calls between two functions

When faced with the task of recursively checking two objects with sorted keys, I came up with a solution involving two functions. buildObj - this function retrieves all unique keys from the objects, sorts them, and then calls buildObjKey for each key bui ...

Ways to process files and verify data correctness?

Today I am exploring the concept of file handling in C and encountered an issue. Initially, I created a text file with the following content: 5 1 5 2 4 -3 The first element represents the size of the array. I implemented a function to read all positive ...

Struggling to understand the concept of JavaScript closures (such as, why is this loop not functioning correctly?)

Similar Question: Understanding JavaScript closures After going through the FAQ and multiple examples, I am still struggling to figure out why my code is not working as intended. Any hints or tips on what I might be doing wrong would be greatly apprec ...

Use the Jquery .one method to target elements sharing a common class

Here is a simple JQuery code example: <script type="text/javascript"> $(document).ready(function(){ $(document).one('focus', 'input', function() { $(this).val(''); }); }); </script> <input ...

Boosting Performance in Three.js - Achieving a Faster Frame Rate

Utilizing Three.js alongside Nvidia's 3D Vision shutter technology has been an interesting experience for me. In my rendering process, I have implemented the following steps: // Setting up the 3D Vision Camera (Shutter Glasses) var eye_separation = 0 ...

Calculations in JavaScript determined by responses provided in the form

I have recently developed a web form that includes various input fields and radio buttons. The purpose of this form is to collect answers from users for cost calculation. However, I am uncertain about the JavaScript logic, especially regarding the radio bu ...

Creating objects that are a fraction of another's width

My goal is to create 3 responsive divs that fill the width of the window and adjust their width based on the window dimensions. However, I'm facing an issue with JavaScript where it seems to be miscalculating the window width, causing the objects to o ...

Creating a PictureBox name using a string - here's how!

Having trouble converting a string to the name of a PictureBox in C#. My form contains 256 PictureBoxes. Currently, I have a string array like this: RanPicture += "Random" + Pic[step1 + 1]; This is used to read data from a text file. What I need is to as ...

Retrieve the google+ user profile in a node application by solely utilizing the access token

Currently, I am working on fetching user profile details in Node.js. The process involves a mobile app that generates an authentication token through the Google Plus native SDK. The token is then sent to my Node server where I aim to retrieve user informa ...

AngularJS Dropdown in ASP.NET MVC 3

I want to create a DropDownList using @Html.DropDownList and connect it with AngularJS. Below is the code snippet: @Html.DropDownList("LessonID", (SelectList)ViewBag.LessonList, "choose one", new { ng_model = "LessonID" }) Here's an example of ...

Why am I unable to access all elements within the map function?

Hey there, I have a function related query. Whenever I try to access my data, I can only reach the first index of each array. For instance, I have 5 different images of PlayStation, but on my webpage, I am only able to see one image. How can I resolve this ...

Utilize $or or $and for incorporating multiple conditions in a match statement

I've seen this question posted before, but I'm having trouble locating the answer. I want to filter shows with flag 1 and flag 2 using $or for searching. How can I include a condition for flag 2 along with flag 1 in my code? Currently, I only ha ...

Populate a Textbox Automatically using a Dropdown List

MVC 4 Changing multiple display fields based on DropDownListFor selection Having some issues trying to implement the solution mentioned above. It seems like there might be a problem with either my javascript code or the controller. JavaScript in View ...

Tips for displaying the property of an array of objects in a template

I am currently trying to display the value of a property in my template, but nothing is appearing. Here is my component code: export class ServerStatusComponent implements OnInit { snovieCollection: SnovietatusDto = {}; constructor(private snovierStat ...

JavaScript is struggling to interpret the JSON string

I am transmitting a JSON string from my Django view to a JavaScript file named idbop.js on the client side. In Django, I am utilizing the serializer to convert query results into JSON format. Here is an excerpt from my views.py file in Django: def index(r ...

Best practices for customizing v-calender in vue.js

I'm struggling with styling my calendar using the v-calendar Vue plugin. I want to customize the background of the calendar, but my code doesn't seem to be working. Can someone please help me out? Thank you in advance. HTML <v-calendar ...