Unlock the Secrets of JavaScript Key Codes

I am currently dealing with a JavaScript routine that I did not create. This routine is triggered by the onkeydown attribute of a text box in order to restrict certain keystrokes.

The first argument does not seem to have any significance. The second argument consists of a list of characters that are allowed.

function RestrictChars(evt, chars) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);

    if ((key == null) || (key == 0) || (key == 8) ||
        (key == 9) || (key == 13) || (key == 27))
        // Control key
        return true;
    else if (((chars).indexOf(keychar) > -1))
        return true;
    else
        return false;
}

This function appears to be functioning properly for alphanumeric characters. However, it seems to return false when characters such as . and / are pressed, despite these characters being included in the chars parameter. For instance, pressing the . key sets key to 190 and keychar to the "3/4" character.

Can somebody clarify how this was intended to work and/or why it is not working correctly? My knowledge of JavaScript is limited, so I'm not able to discern its intended functionality.

Answer №1

There are a couple of issues with the code provided: firstly, when analyzing the character that has been typed, it's important to utilize the keypress event instead of keydown. This is because the keypress event is the only one that reliably provides information about the actual character entered. For more in-depth details on this and JavaScript key events in general, you can refer to . Secondly, there are mentions of a variable named e which should actually align with the evt parameter.

If you have a variable named textBox referencing the text input element, here's an improved version:

jsFiddle link: http://jsfiddle.net/9DZwL/

Code snippet:

function isKeypressCharValid(e, chars) {
    e = e || window.event;

    // Allow delete, tab, enter, and escape keys
    if (/^(8|9|13|27)$/.test("" + e.keyCode)) {
        return true;
    }

    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    var charTyped = String.fromCharCode(charCode);
    return chars.indexOf(charTyped) > -1;
}

textBox.onkeypress = function(evt) {
    if (!isKeypressCharValid(evt, "abc123")) {
        return false;
    }
};

Answer №2

Although I'm not proficient in JS, I can still provide an explanation on how it is meant to function. The reasons behind the values you are receiving for the specified keys are unknown to me.

keychar = String.fromCharCode(key);

This line of code verifies if the key input is a printable character such as a letter or punctuation mark.

if ((key == null) || (key == 0) || (key == 8) ||
    (key == 9) || (key == 13) || (key == 27))
    // Control key

The condition above checks whether the key is null, 0, 8 (backspace), 9 (tab), 13 (ENTER), or 27 (ESCAPE) - producing the expected Boolean result with logical OR operations.

else if (((chars).indexOf(keychar) > -1))

This part of the code examines if the character represented by keychar exists within the string of characters provided through the chars parameter.

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

The webpage is missing a rendered React component even though it should be displayed

I am facing an issue where a React component is not appearing on the webpage despite being rendered. I have provided the code and screenshots of the components below for reference. Below is the snippet from the "App.jsx" file: function createCard ...

What is the origin of the second parameter in an arrow function that returns another arrow function in a React component with Redux?

I'm having trouble understanding where the (val) parameter is coming from in the returned arrow function. I understand that max/minLength is an arrow function taking an argument set on the input field (3 and 25), and it returns another arrow function ...

Utilizing Jquery Validation to Remove a Class Upon Form Validation Success

In my current registration process, I have a multipart form where each subsequent form is displayed when the next button is pressed without fading effects. Initially, the button appears faded. Here's a simplified version of how I handle the first form ...

"Figuring out a way to include a link with each image in a react-s

I am currently working on a project in Gatsby and encountering some issues with the homepage banner. I am using react-slick which seems to be functioning fine, but when I try to add content on top of each image, it causes some problems. Specifically, setti ...

Beware: The use of anonymous arrow functions in Next.js can disrupt Fast Refresh and lead to the loss of local component state

I am currently encountering a warning that is indicating an anonymous object in a configuration file, and even specifying a name for it does not resolve the warning. Below you will find the detailed warning message along with examples. Warning: Anonymous ...

Exploring ways to efficiently test the nested promises in an Angular service function

Here is a snippet of what my service implementation looks like: TestService.initializeDefaults = function() { var qPromise = $q.defer(); $q.all({ localResource: localResource.fetch(), item: itemResource.fetch() }).then(functio ...

the process of extracting data from a request body in Angular 2

After creating a URL for end-users to access, I wanted to retrieve data from the request body when they hit the URL from another module. The process involves fetching the data from the request body, passing it to my service, and then validating the respons ...

How can I effectively set up and utilize distinct npm modules on my local environment?

A React Native component I have created lives in a separate folder with its own package.json file, and now I want to use it in another project. The component named MyComponent is located in Workspace/MyComponent and has specific dependencies listed in its ...

What is the best way to retrieve the most recent CMS posts information within a Gatsby-constructed project?

I created a static website using Gatsby and everything was working well. However, I encountered an issue when updating the titles and content of posts in Contentful CMS - the changes were not reflected when I refreshed the website. How can I ensure that ...

I'm interested in learning about the most efficient practices for handling JSON, performing math operations, and utilizing loops in JS/React. What techniques

Short version: I'm working with a large array of JSON objects (60K+ elements) in my application I need to perform various mathematical operations such as comparison and addition Currently, I am handling this through multiple for loops (simplified ...

Changing Background Color on Div Click

After spending a considerable amount of time on this, I find myself getting confused and stuck. It seems like I might be overlooking something crucial. Essentially, my code is designed to have the default div background (gamebg), and upon clicking one of t ...

Add a new element to the page with a smooth fade-in animation using jQuery

var content = "<div id='blah'>Hello stuff here</div>" $("#mycontent").append(content).fadeIn(999); Unfortunately, the desired effect is not achieved with this code. I am trying to create a sleek animation when adding new content. ...

display different vue component based on screen size

I am in search of a method to implement responsive components in Vue.js (Nuxt). I have developed this mix-in but encountering an error: export const mediaQuery = { data() { return { breakpoints: { sm: 576, md: 768, lg: ...

Steps for resolving the "endless redirection loop" issue in Sharepoint

I am currently learning Javascript and working on setting up a multi-language Sharepoint site. I am trying to implement a code into each page that checks the user's email and the language in the URL (Portuguese or Spanish) and then redirects according ...

Setting up webpack encore for async and await in a Symfony 4 and VueJs project

After setting up a VueJs project within Symfony 4, I encountered an unexpected error involving await and async (Uncaught ReferenceError: regeneratorRuntime is not defined) I've come across plenty of resources for webpack, but nothing specifically for ...

What could be causing my input box to act strangely when users attempt to input information?

I seem to be facing an unusual issue with the <input onChange={this.handleArticleId} value={this.props.articleIdValue} placeholder="article id"/> field. Whenever I try typing something, the letter only appears in the input box after clicking on the s ...

Add a .handlebars or .hbs file to an HTML document

When visiting the emberjs.com homepage, you will find an example of a todo list using Ember.js and Handlebars.js. Within the todo list, there is an extension for a .hbs file. I am curious - what exactly is a .hbs file? And how can I include a .hbs script ...

Using file types in Vue 3: a beginner's guide

In order to use file-type to determine not only the extension but also ensure the headers are correct I would need to use one of the methods listed on their GitHub page. In version 19.0.0 it says fileFromFileType doesn't have such an export and in 16. ...

AngularJS - Use promise instead of returning a data object

I am currently working on a project using AngularJS. Within my service.js file, I am attempting to retrieve some values. However, instead of receiving the actual data, I am getting back a promise object with some $$variables along with the desired data. ...

Tips for showing validation message just one time along with multiple error messages

Exploring ways to implement a dynamic form submit function using jQuery. $('#btnsumbit').click(function() { $('.required_field').each(function() { if ($(this).val() == "") { alert('please fill field'); ret ...