Live data input filtration feature that exclusively accepts numerical values

Hello, I am attempting to create a real-time input filter in JavaScript that only allows numbers and dots. Here is my code:

Javascript:

<script>
function thirdTaskFunction(evnt) {
    evnt = evnt || window.event;
    var charCode = evnt.which ? evnt.which : evnt.keyCode;
    return /\d/.test(String.fromCharCode(charCode));
}

function thirdTaskFunction(evt) { 
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if(charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

function thirdTaskFunction() {
    var thirdInput = document.getElementById("thirdTaskInputText");
    thirdInput = thirdInput.onchange = thirdTaskFuncion;
    var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;
    var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;
    if(!valid.test(this.value)) {
        var compare = this.value.match(number);
        this.value = compare ? compare[0] : '';
    }

}
</script>

HTML:

<div id="thirdTaskDIV">
    <input id="thirdTaskInputText" type="text" placeholder="Type a number" autofocus onkeypressed="return thirdTaskFunction(event);">
</div>

I have tried various methods, but none of the thirdTaskFucntion() functions seem to work. I tested the solution on w3schools, so maybe that's the issue? It seems very similar to "HTML text input allow only numeric input," but it didn't work for me. I hope someone can point out what's happening here.

Answer №1

To restrict an input field to only accept numbers, you can implement a keypress event listener. Begin by identifying the input field and assigning it the event listener as shown below:

     const inputField = document.querySelector("/*input field id here*/");
     inputField.addEventListener("keypress", function(e){
       if(e.keyCode > 48 && e.keyCode < 57){
         e.preventDefault();
       }
     }

This functionality verifies if the pressed key corresponds to a number key. If not, it halts the default action of inserting the character into the input field.

If you have any queries, feel free to ask!

P.S. The keyCodes mentioned are approximations based on memory. For precise key code information, conduct a quick search for "ASCII key codes" on Google.

Answer №2

The dot on the keyboard has an event code called Period, while the numbers 0 to 9 have event codes like Digit0, Digit1, and so forth.

To limit input to only these characters, you can use the keydown event listener along with the includes() method to check if the key pressed matches "Digit" or "Period". If it doesn't match either, you can stop the input by using preventDefault() as shown below:

const input = document.getElementById('thirdTaskInputText');

function checkKey(e) {
  if(e.code.includes("Digit") || e.code.includes("Period")) {
    console.log("valid input");
  } else {
    e.preventDefault();
    console.log("not a number!");
  }
}

input.addEventListener('keydown', checkKey)
<input id="thirdTaskInputText" type="text" placeholder="Type a number">

You can simplify the above code further by combining the condition into a single statement using the bang operator ! like this:

const input = document.getElementById('thirdTaskInputText');

function checkKey(e) {
  if(!(e.code.includes("Digit") || e.code.includes("Period"))) e.preventDefault();
}

input.addEventListener('keydown', checkKey)
<input id="thirdTaskInputText" type="text" placeholder="Type a number">

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

Issue encountered when utilizing ngResource in factory: unable to choose JSON index

ngResource in a factory is functioning properly, but unfortunately, it is only able to select the index of the JSON. However, it is also possible to bind the same variable $scope.resultItems. The console log appears as follows ...

Guide on connecting with a .asmx web service through a basic HTML page

I've been attempting to integrate an asmx web service into a basic HTML page, but I'm not getting any output. The issue is unclear to me at this point. Below is the AJAX code that I have implemented to call the asmx web service. function Getdet( ...

The useState initial value does not seem to update properly when using a Virtual Keyboard

Seeking guidance as a newcomer. Experimenting with incorporating react-simple-keyboard into Gatsby & React. I start my form with a defined state (firstName: "Johnn"). This serves as the initial state. I aim for users to edit this name and store the modifi ...

The Discord OAuth2 bot fails to assign roles to authenticated users

While working on OAuth2 login for my website, I encountered an issue. After a user successfully logs in through OAuth2, the bot should assign a role to them on my Discord server. However, when I tested the login process myself, the bot returned an error me ...

By utilizing the "order" property, I can arrange divs to start at the bottom and ascend as additional elements are added

Exploring the use of display: flex and order:, I noticed a curious behavior. When I set the order for my first div to 0 (order: 0;), it appears at the top of the page. However, as I add more divs with different orders, they initially show up in unexpected ...

What is the reason that other classes in JavaScript do not inherit the static methods of the Object class?

When working with JavaScript, it's interesting to note that creating a class with a static method allows you to call that method using the subclass name as well, since static methods are inherited. The Object class, which serves as the superclass for ...

Using Router.back in Next.js triggers a complete page refresh

I am working on a page called pages/conversations/[id].tsx, and here is the code: import Router, { useRouter } from 'next/router' export default function ConversationPage() { const router = useRouter() ... return ( <View ...

Is it a wise decision to provide the client with a new token just one minute before the expiration of the old one?

When monitoring my backend, I constantly check the remaining time before the JWT expires, which is set to 15 minutes. If there is only one minute left or less, I generate a new JWT and include it in the response header as a setToken. The front-end can then ...

Ajax is malfunctioning and failing to fulfill my needs

I cannot get Ajax to submit no matter what. I've been struggling for hours... script: <script> $(document).ready( $("#submit").click(function(e) { e.preventDefault(); $.ajax({ url: "https://maps.googleapis.com/maps/ ...

Altering the text of dropdown items prior to the ASP.NET autopostback

Recently, I inherited a project from a client that is plagued with some irritating issues. One particular problem involves a dropdown menu that triggers an autopostback event upon selection change, inserting the selected text into a T-SQL query. The troubl ...

Issue: Incorrectly calling a hook. Hooks can only be used within the body of a function component. Assistance needed to resolve this issue

import React, { useState } from "react"; const RegistrationForm = () => { const [name, setName] = useState(""); const [password, setPassword] = useState(""); const [email, setEmail] = useState(" ...

Remove item from the array when the selection changes

Hello there, I am currently working with Angular and I have a multiple select (mat select) in my project. I want to send the selected values as an array. I have tried using selectionChange event and pushing the selected value into an array. However, when I ...

Running an Express application within a nested folder or subpath: a guide

Recently, I set up a basic Express.js application. Here's an excerpt from my main file, server.js: const express = require('express'); const app = express(); app.get('/', (req, res) => { res.status(200).send({ "messag ...

Utilizing Jquery to dynamically update div styling based on text content

I need to modify the appearance of a div based on a number generated by the server. If the number is greater than or equal to 4, I want the progress bar to be green with the title 'superb'. If the number is greater than or equal to 3 but less tha ...

Adjusting the transparency of each segment within a THREE.LineSegments object

I am following up on a question about passing a color array for segments to THREE.LineSegments, but I am looking for a solution that does not involve low-level shaders. I am not familiar with shaders at all, so I would prefer to avoid them if possible. I ...

Creating a layered effect: Adding an image onto another image using HTML and CSS

Wondering if it's possible to create an overlaid effect with an image and text inside of an <img> element, similar to the example image below. Utilizing Bootstrap for this design. This is how I am attempting to achieve it: HTML <div class= ...

Retrieve the latest information and update the database with just one ajax request

I am attempting to update a row in the database and retrieve the updated row one at a time using an AJAX call. JavaScript inside the ready function $("button[name='teacher_lock_exam']").on(ace.click_event, function () { var current_exams_id ...

Obtain the PHP hyperlink value from an AJAX response

I am trying to create a link action to the controller in Codeigniter after receiving a response from AJAX. I need a variable from the AJAX response to include in the link to the controller, where an update process will be carried out. I attempted to use a ...

``Changing the value of the radio button does not update the ng-model variable

I have encountered an issue with my code. Upon page load, the radio button is checked but the ng-model value session.payment does not get updated automatically. I have to manually select it again for the update to take effect. <li ng-repeat="method i ...

Guide on showing a message on the server side when pressing a button in the web browser

I need the following question to function seamlessly on all major browsers including Opera, Internet Explorer, Chrome, Safari, and Firefox I am working on an application that requires users to follow a specific order of pages Text1.php, Text2.php, Text3.p ...