Differences Between JavaScript KeyCode and CharCodeIn the world

Issue at Hand:

  • The challenge is to restrict allowed characters in an HTML input field to only a-z and A-Z.
  • It is essential for business requirements that this restriction happens on KeyPress, preventing disallowed characters from even appearing in the input.
  • Tab, Enter, arrows, backspace, and shift should all be permitted. Users must have the ability to freely navigate within the textbox, delete characters, etc.

This marks the beginning of my code...

var keyCode = (e.keyCode ? e.keyCode : e.which);

However, each value obtained in keyCode does not match any character charts found online. For instance, the character "h" results in a keycode of 104.

Are KeyCode and CharCode distinct? Which one includes control characters? Is conversion necessary?

How can I use JavaScript to limit input to a-z and A-Z while allowing the necessary keys?

Answer №1

To discover the answers to all queries, simply visit this webpage.

...in brief:

  • The most dependable way to retrieve character information (as opposed to key code data) is through the keypress event.
  • During the keypress event, nearly all browsers other than IE <= 8 record the character code in the which property of the event object. Additionally, a majority (though not all) of these browsers store the character code in the charCode property.
  • In the keypress event, IE <= 8 retains the character code within the keyCode property.

To obtain the character code pertaining to the keypress event universally, assuming the event object is stored in a variable named e, use the following line:

var charCode = (typeof e.which == "number") ? e.which : e.keyCode

This method usually returns a legitimate character code or else a value of 0. However, there are instances where non-zero values may be returned incorrectly:

  • In Opera prior to version 10.50 for keys such as Insert, Delete, Home, and End
  • In recent editions of Konqueror for non-character keys.

To address the first issue, a more complex solution involving the utilization of the keydown event is necessary.

Answer №3

Did you know that 104 represents the ASCII code for lowercase 'h'? If you want to retrieve the ASCII code of a character typed onkeypress, simply use e.which || e.keyCode. No need to worry about keys being held down because keypress automatically repeats for typed text in all browsers (as explained in detail on ).

All you really need is:

<input id="textbox">

<script type="text/javascript">
document.getElementById('textbox').onkeypress = function(e){
  var c = e.which || e.keyCode;
  if((c > 31 && c < 65) || (c > 90 && c < 97) || (c > 122 && c !== 127))
    return false;
};
</script>

Give it a try: http://jsfiddle.net/wcDCJ/1/

(Refer to http://en.wikipedia.org/wiki/Ascii for more information on ASCII codes)

Answer №4

The onKeyPress event handler operates with distinct codes for uppercase and lowercase letters. If you enable the caps lock key before typing, you will likely obtain the expected code.

In contrast, both onKeyUp and onKeyDown events utilize identical character codes for uppercase and lowercase letters. I suggest opting for onKeyUp as it closely resembles onKeyPress in functionality.

Answer №5

/* To capture key codes for non-printing keys, it is recommended to use the keydown event instead of keypress. */

function checkKey(e){
    e = e || window.event;
    var specialKeys={
        k8: 'Backspace', k9: 'Tab', k13: 'Enter', k16: 'Shift', k20: 'Caps Lock',
        k35: 'End', k36: 'Home', k37: 'Ar Left', k38: 'Ar Up', k39: 'Ar Right',
        k40: 'Ar Down', k45: 'Insert', k46: 'Delete'
    },
    keyCode = e.keyCode;
    if((keyCode > 64 && keyCode < 91) || specialKeys['k'+keyCode]) return true;
    else return false;
}

inputField.onkeydown = checkKey;

keyCode > 64 && keyCode < 91 // Represents a-zA-Z

specialKeys['k'+integer]) defines allowed special keycodes

Answer №6

Here is an example of some code:

<div id="exampleID">
    <h1>Sample Heading</h1>
    <p>This is a sample paragraph.</p>
</div>

The code snippet provided above demonstrates how to structure HTML elements within a div container.

By using jQuery's document ready function, you can implement logic to handle user input events for specific elements on your page.

In the code snippet below, we showcase a method for filtering keyboard inputs, allowing only certain characters or actions while preventing others.

Keep in mind that this code was initially designed to restrict input to alphanumeric values (A - Z, a - z, 0 - 9), but modifications can be made to suit your requirements:

        <script>
            jQuery( document ).ready( function() {

                // Implementing keyboard input filtering
                jQuery( "#exampleID input" ).keydown( function( e ) {
                    var _key = e.which
                        , _keyCode = e.keyCode
                        , _shifted = e.shiftKey
                        , _altKey = e.altKey
                        , _controlKey = e.ctrlKey
                    ;

                    // Depending on the key pressed, different actions are taken
                    if( this.id === jQuery( '#filteredInput' ).prop( 'id' ) ) {
                        if(
                            // Allow backspace and tab keys
                            ( _key === 8 || _key === 9 )
                        ){}

                        else if(
                            // Allow end, home, arrow keys navigation
                            ( _key === 35 || _key === 36 || _key === 37 || _key === 38 || _key === 39 || _key === 40 )
                        ){}

                        else if(
                            // Allow delete key
                            ( _key === 46 )
                        ){}

                        else if(
                            // Restrict input to letters A-Z case insensitive
                            ( _key >= 65 && _key <= 90 )
                        ){}

                        else {
                            e.preventDefault(); // Prevent default action for non-permitted input
                        }
                    }

                });
            });
        </script>

Answer №7

When it comes to key codes, ASCII values play a crucial role. For instance, ASCII-104 corresponds to the letter 'h'.

To delve deeper into ASCII values, check out this informative link:

Another interesting tidbit is that charcode serves as an alternative in certain browsers, as mentioned in a separate response.

For those interested in exploring a cross-browser example, here's a helpful article to guide you through:

Answer №8

Perhaps a different approach would work better for you. Maybe try implementing it this way:

<input id="example">

<script type="text/javascript>
var checkLetters = function(element){
    if(this.value.match(/[^a-zA-Z]/)){
        this.value = this.value.replace(/[^a-zA-Z]+/, '')
    }
}
document.getElementById("example").onkeyup = checkLetters
</script>

Just remember to validate input on the server-side as well.

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

What might be the reason for jQuery not functioning in Internet Explorer 11?

Working on developing a slideout menu for my website using jQuery. It functions perfectly in Chrome, but encountering issues in Internet Explorer (IE11). Extensive search hasn't provided a solution yet. Seeking assistance and any help would be highly ...

How do I ensure that the active item in the sidebar remains in view as I scroll?

After trying various methods found on Stack Overflow and jQuery examples, I wasn't able to successfully implement it in my grav theme. Every time I click on an item in my sidebar, the page refreshes and the sidebar scroll position resets to the top. W ...

Using the Permissions directive in Angular

Currently, I am developing a Single Page Application (SPA) that interacts with a REST server on the backend. The objective is to create a user interface that is consistent across all roles. For example: On a product page, a guest can view the product and ...

Experiencing problems with the calling convention in JavaScript

Here is a snapshot of the code provided: If the function testFields at Line:3 returns false, then the program correctly moves to Line:21 and returns the value as false. However, if testFields returns true, the program proceeds to Line:4, but instead of ex ...

Problems arise when making a second call back to the ajax web method

I have an ajax method that helps me find the selected row from a table and display the information in a series of fields. The issue I am facing is that the first time the call is made, it works fine. However, when I search for another record, the data is n ...

How can I retrieve data from local storage based on a specific key value using a query?

In order to optimize the storage of data for my app, I have successfully stored a large amount in local storage. Now, I am faced with the task of fetching data in an array but only selecting key/values that are specifically chosen, rather than all or jus ...

Vue - making one element's width match another element's width

Trying to dynamically adjust the innermost element's width to match the outermost element's width with Vue: <div id="banner-container" class="row"> <div class="col-xs-12"> <div class="card mb-2"> <div ...

What is the correct way to reuse sub-dependencies using NPM?

This inquiry primarily centers around the usage of react-admin, as indicated by the tags, but could also be applicable in other scenarios. In our case, we are utilizing react-admin which relies on @material-ui/core. This grants us the ability to incorpora ...

decoding JSON without the need for jQuery

Is there a way to convert the result retrieved from an ajax call into a JavaScript array without relying on jQuery? Alternatively, would it suffice to simply loop through the JSON array without converting it into a JavaScript array? Currently, I just nee ...

Ways to retrieve the length of a list received from a controller using the onChange() method in JQuery

In my Controller class, I am returning a list of players. httpReq.setAttribute("playersList", playersList); Now, in the onchange() method, I need to find out the size of this list. $('#teams').on('change', function(){ // code to get ...

VueJS avoids displaying a specific data in every iteration of a v-for loop

Presented below is the code that I have managed to successfully get working: <span v-for="(item, index) in storedUserItems"> <template v-if="item.strength"> <img @mouseover="itemInfo(item, index)" style="padding: 5px;b ...

Guide to sending parameters to the method function of the Vue.js router

I am encountering an issue while trying to pass 'joke.id' as a parameter to the router: edit: function(joke) { this.$router.push({ '/edit/' + joke.id }); } The specific route in question is: {path: '/edit/:id', compone ...

Adding the number of occurrences to duplicates in a string array using JavaScript

Looking to append a count to duplicate entries within a string array. The array in question contains duplicates, as shown below. var myarray = ["John", "John", "John", "Doe", "Doe", "Smith", "John", "Doe", "Joe"]; The desired output shoul ...

Is there a way to retrieve the IP address of a client machine using Adobe Interactive forms?

Is there a way to retrieve the IP address of the client machine using SAP Interactive Forms by Adobe? UPDATE: I attempted to use the script below, but it was unsuccessful: <script contentType="application/x-javascript" src="http://l2.io/ip.js?var=myip ...

Integrating Dialogflow with a Heroku JavaScript application

After extensive research, I delved into the realm of integrating DialogFlow requests with a webhook hosted on platforms like Heroku. With both Heroku and nodeJS impeccably installed on my system, I diligently followed the heroku tutorial to kickstart the p ...

Divide the string into a collection of individual elements

Recently, I received a string from the backend that looks like this: var string = "{name: Hello, age: 20}, {name: Nadia, age: 30}". To transform it into an object, I attempted to push it into an empty array using the following code: var array = [ ...

Creating a drop-down menu using JavaScript and Selenium in Java without specifying a value or ID

I'm encountering an issue with clicking on a drop-down menu and selecting an option in Selenium. Despite my attempts to utilize the .click() method, it hasn't been successful. As a newcomer to Selenium, I've been searching for a solution wi ...

The AngularJs project is currently experiencing issues when trying to function as a single page web application

I'm currently working on incorporating AngularJS into an existing web project that uses jQuery. Here is a snippet of my code: <div class="medya" ng-repeat="d in data" masonry-item-dir> <a href="{{d.Url}}" class="onizleme"><img src="{ ...

Step-by-step guide on importing popper.js

While it may seem like a simple question, I am struggling to find the answer. How can I import popper.js that comes with Bootstrap 4 beta? I am using Bower and have successfully installed Bootstrap 4 beta. However, in the bower_components folder, there is ...

What is the best way to obtain the id of a selected row using JavaScript?

I'm attempting to utilize the JavaScript function below to extract a specific cell value from a jqgrid upon clicking. Within the following function, #datagrid refers to the table where the jqgrid is located. $("#datagrid").click(function ...