Please enter only numerical values using jQuery

Currently, I am facing a slight issue. My goal is to only run the code when the input characters are numbers.

This is the snippet of code I have been working with:

$(".jq-sales, .jq-variablecosts, .jq-fixedcosts, .jq-additional-sales, .jq-sales-units, .jq-variablecosts-units, .jq-totalsold-units").keypress(function(event) {
      if (event.keyCode >= 48 && event.keyCode <= 57 && event.keyCode >= 96 && event.keyCode <= 105) {
        event.preventDefault();
      } 
      else {
        // Continue with my actions
      }       
    });

What could be the issue in my code?

I am aiming to accurately detect input from both the numpad and the number keys above the keyboard as well.

Answer №1

Your situation seems to present a contradiction

  if (event.keyCode >= 48 && event.keyCode <= 57 && event.keyCode >= 96 && event.keyCode <= 105) {

It is not possible for a number to fall within the ranges of both 48 to 57 and 96 to 105 simultaneously.

  if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {

You should utilize the logical OR operator (||) here

Additionally, make sure that your action is performed when the condition is true, not false.

  if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {
      // perform your desired action here
  } else {
      // do nothing
      event.preventDefault();
  }

Answer №2

Your current conditional logic is flawed. You are trying to restrict the keyCode to be less than or equal to 57 AND greater than or equal to 96 simultaneously, which will never be true.

In addition, even if you were to fix that issue, you would still be blocking number keystrokes and running your code on non-number inputs.

To correct this, you should consider the following approach:

$(".jq-sales, .jq-variablecosts, .jq-fixedcosts, .jq-additional-sales, .jq-sales-units, .jq-variablecosts-units, .jq-totalsold-units").keypress(function(event) {
    if (
            ( event.keyCode >= 48 && event.keyCode <= 57 ) ||
            ( event.keyCode >= 96 && event.keyCode <= 105 )
        )
    {
        // Perform desired actions
    } 
    else {
        // Ignore non-numeric input
        event.preventDefault();
    }       
});

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

Odd behavior observed in the Android browser while choosing input fields

When stacking modal elements in the Android Webkit browser (tested on versions 2.2, 2.3, and 3.0), strange behavior seems to occur. Take this example: Here, I have a jQuery UI date picker with z-index 200, a gray overlay div covering the entire document w ...

Incorporating an additional row into a material table

Currently, I have implemented a mat-table with various features including drag and drop functionality and dynamic columns. However, I am facing an issue while trying to add row filters under the table header. I attempted to simply insert a <mat-row> ...

Determine if the object's value is present

My current JavaScript setup looks like this: var NAMES = []; function INFO(id,first,middle,last){ var newMap = {}; newMap[id] = [first, middle, last]; return newMap ; } Next, I have the following code block: for (var j = 0; j < NUMBER.leng ...

Could a css style be applied to a parent element based on the status of its child element?

In my specific context, this is the HTML code I have: <div class='table'> <div> <div *ngFor='let product of this.market[selectedTab].products | orderBy:"id"' class='itemlist' [ngClass]="{' ...

Adjust the header width and column alignment when freezing the header in a gridview interface

Looking to implement a gridview with a fixed header? I've tried various solutions including this link and this one. While I've managed to get it working, the main issue lies in the alignment of header width and column width. The scroll and freez ...

Having trouble getting the `nth-of-type` and `nth-child` selectors in CSS to function

I am attempting to apply a green color for the first nth child flag element <div id="axis"> <div class="super"></div> <div class="flag">flag 1</div><!-- I want this text to be green--> <div class="supe ...

How can a color gradient blend be applied to geometry on multiple axes using THREE.JS shader?

After referencing Apply color gradient to material on mesh - three.js I successfully implemented a flower shader that applies a vertical color gradient across the Zinnia. The colors transition from red to yellow vertically, creating a gradient based on he ...

What is the best way to structure a data object in Javascript or VueJs?

As I work on developing a small application using VueJs, the data I receive is structured in a particular format: { "interactions":[ { "id":14, "user_id":1, "schedule":"2017-06-04 05:02:12", "typ ...

Extract values from JSON object and store them in an array, then apply them in an external

I have created an axios JSON data call function and I am looking for a way to extract values from my jJSON function so that they can be used outside of the function. Is there a method to achieve this? Below is my code snippet: let website_names = `${api} ...

Onload, capture page elements, delete them, and then access the original content

I am encountering two DIV elements on my page that I need to capture upon loading the page and preserve their contents until the page is refreshed. The nested DIV element is contained within the other one. After locating these elements initially, I want t ...

Is it possible to alter the background behind each word in a text using only CSS?

I have a question about styling quotes by highlighting each word in the text with a background color. The issue I'm facing is that when using a solid background, there are no gaps between the colors. How can I achieve a result similar to this, but wit ...

Fixed position halting in a specific area

I have a fiddle where the black box is fixed on the page, but it overlaps the map when scrolling. I want to stop the black box from overlapping the map. How can I achieve this? CSS: .item{ background:#eee; padding:10px; width:50%; margin-bottom:15px;} .n ...

Modifying the disabled attribute of an input tag upon button click in Angular 2

I am currently working on a function in Angular 2 where I want to toggle the disabled attribute of an input tag upon button click. Right now, I can disable it once but I am looking to make it switch back and forth dynamically. Below is the HTML template c ...

Utilize Bootstrap4 to position content above the navigation icon

I need assistance to modify my code so that it will have the following appearance: I successfully created a navigation bar icon and inserted the logo, but I am struggling to position the data above the navigation icon: My current code: <nav class="n ...

When employing UI-Router, custom directives may not function properly within nested views

I was developing an angular application using phonegap, ionic, and angular. I had created a custom directive that registered an event listener for the element to activate iScroll upon loading. Initially, the directive worked perfectly when all the views we ...

How can I create a circular Datepicker in JavaFX?

Struggling with customizing my JavaFX application using CSS. Everything was going smoothly until I encountered the Datepicker. Despite trying various approaches, none seem to be working. Is there a way to round the Datepicker just like my TextFields? Here ...

Encountered an issue with reading the property 'drop' from an undefined source during a straightforward migration

I recently started using the migrate-mongo library and encountered an issue during a simple migration process to create a view. Despite success in migrating up, I faced an error when attempting to migrate down. ERROR: Could not migrate down 20220620114132 ...

Having Trouble with Gulp and AutoPrefixer Integration

I have integrated Gulp into my project and am looking to utilize the autoprefixer feature. Here is a glimpse of my current gulp file: // Including gulp var gulp = require('gulp'); // Including necessary plugins var concat = require('gulp-c ...

Browsing through different pages on a Rails app will trigger numerous requests to various destinations

My application consists of a landing page and a profile page. The relevant parts of my rake routes are: index GET /welcome/index(.:format) welcome#index show GET /profile(/:username)(.:format) sessions#show root / ...

Utilize ajax to round the floating point number

When working with JSON data, I extract the values and attempt to round them using the script below: function onLoad(){ var output = $('#product'); var id = getUrlVars()["cPath"]; $.ajax({ ...