Accept only numerical values, addition and subtraction symbols, commas, the F5 key, and various other characters

I want to restrict key strokes to only numbers (including those on the numpad), minus (-) and plus (+) signs, and commas (,).

Currently, it types twice when I input a number (e.g. 2 is displayed as 22) and replaces the current value with the new number. For plus, minus, and comma keys, it shows ½, m, and k respectively. I also need to allow common website shortcut keys like F5, Ctrl + R, Shift + R, delete, home, and end. However, I'm not sure how to unblock F5, Shift + R, and Ctrl + R.

$('body').on('keydown', 'input[name="textfield-correction-temperature"]', function(c) {
    console.log(c.keyCode);
    if(c.keyCode != 107 && c.keyCode != 109 && c.keyCode != 188 && c.keyCode > 31 && (c.keyCode < 48 || c.keyCode > 57)) {
        return false;
    } else {
        var key = String.fromCharCode(c.which);
        $(this).val(key);
    }
});

View demo on jsFiddle

Answer №1

To simplify your code, consider using a regular expression in this process.

For example, here is a snippet that utilizes a regular expression to filter out anything that is not a digit:

$(document).ready(function() {

    $('body').on('keydown', 'input[name="textfield-correction-temperature"]', function(c) {

        if (String.fromCharCode(c.keyCode).replace(/[^0-9]/g, '') == '') {
            return false;
        }

    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="textfield-correction-temperature" tabindex="0" maxlength="6">

You have the flexibility to customize the regular expression to fit your specific needs by adjusting acceptable and unacceptable characters.

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

Utilizing Node.js createReadStream for Asynchronous File Reading

For a specific project, I developed a module that is responsible for splitting files based on the '\r\n' delimiter and then sending each line to an event listener in app.js. Below is a snippet of the code from this module. var fs = req ...

Issue with ng-grid in AngularJS: Data does not appear after resizing columns

Currently, I am encountering a problem where ng-grid data is not being displayed when column resizing occurs after changing the column names. To demonstrate this issue, I have created a plunkr at - http://plnkr.co/edit/eV9baoDOV9A46FZmKW8G?p=preview I wo ...

Only a single element in the array is being pushed by the JavaScript code, not all elements

Having an issue with my script where it is only returning one element out of a class that has 10 elements. Can anyone help me pinpoint the problem? `function() { var vins = document.querySelectorAll('.dws-vehicle-listing-item-field.dws-vehicle-field- ...

Customizing content based on Route - Utilizing Node.js/React

I am currently working on setting up routes for different pages of store profiles in my Node app. I have been doing some research online and have come to understand how to adjust the parameters, but I am struggling with figuring out how to dynamically chan ...

Using express.static can cause an issue with a Nodejitsu application

I'm completely puzzled by this issue that keeps cropping up. Whenever I try to add a static path to my app, I encounter an error on the hosting platform I use called "nodejitsu". The error message indicates that the application is not functioning prop ...

Incorporating external JavaScript into a Rails application

Having trouble with the syntax on this simple problem. Struggling to find examples of externally linked files, all solutions online involve storing a local copy instead. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" typ ...

Create artwork by drawing and adding text to an image before saving it

I am looking to enhance my website by adding a feature that allows users to draw on images hosted on the server. Additionally, I want users to have the ability to add text to the image and save their edits as a new picture. While it may seem like a simple ...

Retrieve Checkbox within a Span using Jquery

Trying to achieve the selection of a checkbox when a user clicks on a div using jQuery. The provided fiddle shows my attempt: http://jsfiddle.net/5PpsJ/ The code snippet I have written so far is as follows, but it doesn't seem to select the checkbox ...

Exploring Angular14: A guide to efficiently looping through the controls of strictly typed FormGroups

Currently, I am working on upgrading my formGroups to be strictly typed in Angular v14. Within my FormGroup, there is a specific block of logic that iterates through all the controls and performs an action (this part is not crucial as I am facing issues be ...

A Guide to Organizing Vue Js: Dividing 'methods', 'data', 'computed', and More into Separate JavaScript Files

Is it feasible to separate methods, data, computed properties, etc. into individual .js files and then import them into a component.vue file? I prefer not to include all JavaScript logic in a single .vue component. My ideal code organization for each com ...

Steps for customizing the dropdown arrow background color in react-native-material-dropdown-v2-fixed

Currently, I am utilizing react-native-material-dropdown-v2-fixed and I am looking to modify the background color of the dropdown arrow. Is there a way for me to change its color? It is currently displaying as dark gray. https://i.stack.imgur.com/JKy97.pn ...

Generating a header each time a table is printed across multiple pages

A table has been created in a webform using C#. The goal is to only print the table when the user clicks the print button on the webform. Javascript has been implemented in ASP.NET to only print the content within a specific div. While this method works, ...

how to set up automatic login for a user after changing their password using passport-local-mongoose

Trying to automatically log in a user, but encountering an issue with the current 'update' function that looks like this exports.update = async (req, res) => { const user = await User.findOne({ resetPasswordToken: req.params.token, re ...

Is the window frozen while Ajax processes the request?

When I make an ajax request that may take a significant amount of time to process on the server-side, I want to display a loading image during the request. However, the loading image is not showing up while the ajax request is processing. var ref = create ...

Using routes with optional parameters can inhibit the loading of other routes

In my Node.js app based on Express, I have implemented three different routes. app.get('/', function (req, res) { // }) app.get('/findOne', function (req, res) { // }) app.get('/getFour', function (req, res) { // }) Init ...

Tips for resolving the issue of receiving a warning about passing "onClick" to a "<Link>" component with an `href` of `#` while having "legacyBehavior" enabled in Next.js

My current project is displaying a lot of warnings in the browser console and I'm unsure about the reasons behind it. The warnings include: "onClick" was passed to with href of /discovery/edit but "legacyBehavior" was set. The l ...

Having trouble getting THREE.Raycaster to intersect with THREE.PointCloud

Currently, I am trying to implement click events on my WebGL based 3D graph library called Graphosaurus. You can take a look at what I have done so far here. I have used this example as a reference. I am wondering if the reason it is not functioning corr ...

The jQuery dropdown selection for only displaying the month and year is not functioning properly when using the select

Currently, I am utilizing a datepicker with only the month and year as options to select from using dropdowns. However, when I apply the following CSS to disable the days of the datepicker, it ends up affecting all datepickers in my JSP file. 1. Is there ...

Error message: "jQuery is not defined and occurs exclusively in Chrome."

I've been using the following code to asynchronously load my JavaScript in the head section: <script type='text/javascript'> // Add a script element as a child of the body function downloadJSAtOnload() { var element4= document.creat ...

Javascript code that enables me to specify the type of weather

My intention with this code was to create unique characteristics for different weather types and randomly select one by generating a random number. I defined 11 different weather types as objects of the Weather class. I then implemented a getWeather funct ...