Key code problem - Struggling to block the entry of the % symbol

On my HTML page, I have an input text field that should only accept number keys and left/right arrow on the keyboard. I attempted to implement this using JavaScript, but encountered a problem.

<input onkeypress="return allowNumberOnly(event)" />

function allowNumberOnly(event) {
    event = event || window.event;
    var charCode = (event.which) ? event.which : event.keyCode;

    //keyCode 48-57 represent the number 0-9
    //keyCode 37,39 represent the Left and Right arrow
    //keyCode 46 represent the Delete key
    //keyCode 8 represent the Backspace key

    return charCode == 37 || charCode == 39 || charCode == 46 || charCode == 8
              || (charCode >= 48 && charCode <= 57);
}

Upon testing, I discovered an issue where both the keyCode for the left arrow and the % special character are 37. This causes a conflict as I cannot prevent the entry of the % character while allowing the left arrow. I am puzzled by this unexpected behavior as I always believed each key on the keyboard would have a unique keyCode. I considered using onkeyup instead of onkeypress, but that would permit users to enter invalid characters first before removing them from the input text, which is not ideal. Any suggestions on how to address this issue?

Further debugging in FireFox revealed the following discrepancy:

1. Pressing % results in event.which == 37 and event.keyCode == 0
2. Pressing the Left Arrow results in event.which == 0 and event.keyCode == 37

By leveraging this difference, it seems like the problem has been resolved. I will continue to test in IE and Chrome to ensure consistent behavior.

Answer №1

For more information on Keyboard events, check out this link:

In addition, I have created a jQuery version of the code:

$('input').keypress( function( e ){ 

    var code = e.which || e.keyCode ; 

    if ( !( e.shiftKey == false &&
            (
               code == 46 ||
               code == 8 ||
               code == 37 ||
               code == 39 ||
               ( code >= 48 && code <= 57 ) 
            )
         )
    ){

         e.preventDefault();                   
    }

});

You can test it out at http://jsfiddle.net/UGpUJ/

Answer №2

View Bryant Williams' solution to this query:

How do I monitor arrow key usage in Chrome and IE?

His recommendation includes verifying if charCode==0, or checking for the presence of the shift key being pressed.

Answer №3

A while back, I devised the following solution on a coding forum:

var numbersOnly = function(e){
    var charCode = (typeof e.which === "number") ? e.which : e.keyCode,
        chr = String.fromCharCode(charCode); //convert it to a character

    if(isNaN(parseInt(chr, 10))) e.preventDefault();
}

To implement this method, use the following:

<input type="text" name="phoneNumber" onkeypress="numbersOnly(event);">

The approach involves obtaining the key code used, converting it to its equivalent char code, and then analyzing the char code rather than the key code. In my experience, this technique has proven to be more effective compared to others I have encountered, and it functions smoothly.

Here is an example on JS Bin.

Answer №4

To detect key presses, utilize the onKeydown event. In this case, the keycode for the % symbol is 53.

For further reference on checking keycodes, please visit the following links:

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

How can I determine if a URL in react js includes a specific string?

I am working on a project where I need to check if a given URL contains the string youtube using react hooks in React JS. This is what my current code looks like: useEffect(() => { let srcLink = "www.google.com/https://img.youtube.com/vi/h9-qcy3HQn ...

Is it possible to convert an object with properties of equal length into a list of objects using JavaScript?

I am working with an object that has multiple keys, each containing a list of equal length: myobj = { 'key1' : [1, 2, 3], 'key2' : ['a', 'b', 'c'], 'key3' : [true, false, true], .. ...

Removing items from a todo list in JSX without relying on props or state

I am facing a challenge with utilizing a function to delete an item from an array when clicking the delete button. I am seeking a solution without relying on props or state. Could someone please point out where I may be making a mistake? The item appears ...

Utilize Angular 2 to search and filter information within a component by inputting a search term from another component

In my application, I have a Component named task-board which contains a table as shown below: <tr *ngFor="let task of tasks | taskFilter: searchText" > <td>{{ task.taskName }}</td> <td>{{ task.location }}</td> <td>{{ ta ...

Instantiating a Google Cloud Function with a Real-Time Database Trigger Path

Looking for advice on Google Cloud functions triggered by RTDB - specifically, how to access the trigger path of an existing function. I'm encountering an issue when copying functions for different environments (dev vs. production) as the trigger path ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

Why is the HTML5 audio player only playing the first two songs in the array?

Why do only the first 2 songs play and then nothing happens? I want them to keep playing through the entire array of songs. Additionally, my rewind button is not working as expected - when clicked, it should go back to the previous song in the array and if ...

Retrieve the HTML tags following the modification of my information in ASP.NET

Apologies for any language errors, I am new to asp.net development. 1- I have a table with dynamically created rows and columns based on user selection of row and column numbers. 2- Each row in the table has the following controls: A- One textbox, one l ...

Tips for implementing a controlled RadioGroup in React: Mapping through an array of values to dynamically populate radio buttons

I have a scenario where I am utilizing a pre-defined set of arrays to populate multiple RadioGroups. The component hierarchy in the codesandbox is structured to resemble that of my actual project. Whenever I select a radio button, I receive an error messa ...

Changing properties of JavaScript arrays

Currently using Express and dealing with an array of objects that I need to adjust the created property for better presentation, utilizing the dateFormat package. The array originates from a mongo query and is stored in a variable called stories. A sample ...

Issue with React redirect not functioning post transition

A component I created includes a redirection route that triggers after an animation finishes. Here is the code for reference: Menus.jsx class Menus extends Component{ constructor (props) { super(props); this.state = { select: 'esp ...

Accessing user input upon button press

I am facing a challenge in displaying my emailInput on my createPassword page, specifically where [email protected] is mentioned. I have provided the code snippets for both pages below, the email page containing a user input and the password page wher ...

VueJS - Building a Form Template Within a Modal Component

Struggling to include a template in a modal and unsure how to pass variables to the child template: Below is the main HTML for the application: <div id="example" class="container"> <button class="btn btn-primary" type="button" @cli ...

Merge objects based on specific property within an array of objects

Is there a way to merge objects based on one property and also add missing Days names in the output? Consider this example: var array = [ { "heure1": "14:00", "heure2": "17:00", "day&q ...

Exploring the functionality of the onClick event handler in React

As a beginner in React, I am currently immersing myself in learning the framework from scratch. While I have successfully constructed some basic components for a restaurant website, I am encountering challenges when it comes to comprehending event handling ...

Following the build process with the --prod flag in Ionic 3, users may encounter a situation where

Encountering an issue only when using --prod on Android phones. Strangely, touching anywhere triggers the event that should be fired at that specific location, causing the content to suddenly appear. I came across information suggesting a conflict between ...

jQuery - Enhancing User Experience with Dynamic Screen Updates

Is there a way to update the screen height when resizing or zooming the screen? Whenever I zoom the screen, the arrows break. I'm also curious if the method I'm using to display images on the screen is effective. It's supposed to be a paral ...

Creating Responsive Image Map Areas in HTML

Implementing image maps on my website has been a challenge because of the lack of responsiveness. I am struggling to adjust the size of map areas when resizing the window. If anyone can help with this issue, I am open to using either JavaScript or CSS met ...

Tips for verifying that jQuery is functioning correctly and that the Jquery.min.js file has been properly loaded

My code usually functions correctly, but occasionally when I input data into the database, it returns output as JSON. Most of the time, the response contains "success" in JSON format, but sometimes I receive the complete JSON output. I have two main pages ...

Error: Unable to access the 'rotation' property of an undefined object in the animate function on line 266 of index.html, at line 287 of index.html

I am facing an error when trying to animate a model with rotation or position in my code. I attempted to create an init function to run everything, but it did not resolve the issue. The error only appears during animation; once the animation stops, the e ...