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

Content within a Row of a Data Table

Hello! I am just starting to learn JavaScript and jQuery. Can you help me with an issue I am experiencing? Basically, I have a table and I need to identify which tr contains a td with the text "Weekly", "Daily", or "Monthly". Once I locate that specific t ...

It is impossible for me to invoke a method within a function

I am new to working with typescript and I have encountered an issue while trying to call the drawMarker() method from locateMe(). The problem seems to be arising because I am calling drawMarker from inside the .on('locationfound', function(e: any ...

How can React and Redux ensure that response data is accessible to every component?

When using react and redux, how can data written in the useDispatch function be made available in other components? Additionally, how can the customerId be accessed in all components? I have created a code that calls an API and returns data in response. I ...

What is the method for incorporating locales into getStaticPaths in Next.js?

I am currently utilizing Strapi as a CMS and dealing with querying for slugs. My goal is to generate static pages using getStaticPaths and getStaticProps in Next.js. Since I'm working with multiple locales, I have to iterate through the locales to re ...

What is the proper way to document instance members that have been added through Object.defineProperties()?

I am struggling with JSDoc 3 recognizing instance properties defined using Object.defineProperties in my class. Here is a simplified version of the code I am working on: /** @exports mymodule */ function mymodule(exports) { /** @constructor * @p ...

What is the purpose of assigning scope.property to scope.property() in order for the expression to function properly?

I have encountered an interesting situation with the directive below. In order for my expressnum function to work in the template, I had to include the line scope.expressnum = scope.expressnum();. It does what I need it to do, but I'm not entirely sur ...

The response from Axios in NodeJs is displaying incorrect encoding

Having some trouble executing a REST call using Axios and receiving an unexpected response. try { const response = await axios.get("https://api.predic8.de/shop/products/"); console.log(response.data); } catch (error) { console.log(`[Error] -> ...

How to iterate through a "for" loop in JavaScript using Python-Selenium?

In my current project, I am utilizing Javascript to gather data from an HTML page using Selenium. However, I am facing a challenge where I am unable to execute the multi-line for loop in the Javascript portion on my computer through Selenium with Python (S ...

The correct reading of JavaScript in HTML is a common source of confusion

After creating a basic application using the code provided in a forum thread and testing it on the worker sandbox MTurk site, I noticed a peculiar issue. The application runs smoothly when following the code from the forum answer directly. However, when at ...

What is the most effective way to display a card with varying values depending on the user's input in a form?

For a while now, I've been grappling with a particular challenge. In my project, I am utilizing multiple states to display values within a card after they are entered into a form. The first state captures the values and modifies the initial state, whi ...

Transferring an organized array to processing

My goal is to transfer an array of integers from a php file called load.php to a JS script, which will then forward it to a Processing file written in JavaScript. In load.php, I define the array and send it using JSON (the array contains a minimum of 40 i ...

When using mongoose, is it possible to add a new item and retrieve the updated array in one endpoint?

My API endpoint for the post operation query using mongoose is not returning the updated array after adding a new item. I have been struggling with this issue for 3 days without any success. Any help would be greatly appreciated. router.post("/:spot ...

Incorrect posture during the movements

Utilizing Jquery Drag and Drop, I have implemented two swap-able divs. However, during the animation process of swapping the divs, their positions are not properly maintained. The actual swapping of the divs works correctly, but there is an issue with the ...

What could be causing the target to malfunction in this situation?

Initially, I create an index page with frames named after popular websites such as NASA, Google, YouTube, etc. Then, on the search page, <input id="main_category_lan1" value="test" /> <a href="javascript:void(0)" onmouseover=" window.open ...

What is the process for sending JavaScript data to a Rails controller action?

Utilizing jQuery Shapeshift for drag and drop reordering of lists on my web application. I am looking to send the data below to my Rails controller action in order to update the list's order. Every time I drag a list, this is the output that appears ...

Are we looking at a declaration of an arrow function? Is this concept even real?

I have been exploring the concept of function expressions versus function declarations with arrow functions. From my understanding, this is an example of an arrow function expression: const fred = greeting = () => { console.log("Hello from arrow ...

Solution for Organizing Tables

I've sourced data from various JSON API links and displayed it in a table. Currently, my code looks like this: <script src="js/1.js"></script> <script src="js/2.js"></script> Above this code is the table structure with <t ...

The functionality of the Bootstrap carousel for moving to the next and previous images is malfunctioning, as it only

The carousel on my website is not functioning properly. It only displays the first image and does not slide to the next pictures as it should. Here is the code snippet for the carousel: <body> </nav> <div id="carousel1" class="carousel slid ...

Retrieve data from a REST API in a dynamic manner without manually specifying the table structure in the HTML code

I am looking to retrieve JSON data via a post request from a REST API: http://localhost/post1 param1='1' The response will look like this: { "json_table": [ { "date": 123, "test": "hello2" }, { "date": 19, ...

Ways to terminate all AJAX requests within a for loop

Is there a way to cancel all AJAX requests that are being handled by a for loop? var url = ["www.example.com","www.example2.com",....]; for (var i = 0; i < url.length; i++) { var XHR = $.get(url[i], function(data) { //do something }); } I attemp ...