JavaScript decimal validation not functioning as intended

Hey everyone! I've created a script that restricts textboxes to allow only decimal numbers. Take a look at the code snippet below:

function onlyDecimal(evt) {
        if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57)))
            return false;
        var parts = evt.srcElement.value.split('.');
        if (parts.length > 2)
            return false;
        if (evt.keyCode == 46)
            return (parts.length == 1);
        if (parts[0].length >= 15)
            return false;
        if (parts[1].length >= 3)
            return false;
    }

<asp:TextBox ID="txtDecimal" runat="server" OnKeyPress="return onlyDecimal(event)" />

As it stands, this script only allows inputs like:

1.000
12.000
123.123

However, I'm looking to enhance it to accept inputs like 1234.123,12345.123 and beyond. Can someone lend a hand?

Another issue I've encountered is that when I try to edit the decimal part after entering a number like 12.123, it doesn't allow me to edit the value until I clear the input. Any advice on how to address this?

Answer №1

If you want to enhance the functionality of your textbox, you can simply add the "FilterNumber" class to it and use jQuery for implementation.

<asp:TextBox ID="txtDecimal" CssClass="FilterNumber" runat="server" />

$(".FilterNumber").live("keypress", function (e) {    
    var caretPosition = doGetCaretPosition(this);
    var code = (code ? code : e.which);
    // Allow delete and navigation keys
    if (code == 0 || code == 8)
        return true;
    var Value = $(this).val();
    if (Value.indexOf('.') != -1) {
        var splt = Value.split('.');
        var indexofDot = Value.indexOf('.');
        if (caretPosition > indexofDot) {
        // Allow only three characters after .
            if (splt[1].length > 2) {
                return false;
            }
        }
        else {
            // Allow only fifteen characters before .
            if (splt[0].length > 14) {
                return false;
            }
        }
    }
    if (code != 46 && code > 31 && (code < 48 || code > 57))
        return false;
    // If it is (.)
    else if (code == 46) {
        var Value = $(this).val();
        // If value already contains (.) character
        if (Value.indexOf('.') != -1) {
            var splt = Value.split('.');
            // If there is already (.) char then return false
            if (splt.length >= 2)
                return false;
        }
    }
    return true;
});

Understanding the caret position on the textbox is crucial for determining if the user is inputting numbers before or after the dot.

function doGetCaretPosition(oField) {
    // Initialize
    var iCaretPos = 0;
    // For IE Support
    if (document.selection) {
        // Set focus on the element
        oField.focus();
        // To get cursor position, get empty selection range
        var oSel = document.selection.createRange();
        // Move selection start to 0 position
        oSel.moveStart('character', -oField.value.length);
        // The caret position is selection length
        iCaretPos = oSel.text.length;
    }
    // For Firefox support
    else if (oField.selectionStart || oField.selectionStart == '0')
        iCaretPos = oField.selectionStart;
    // Return results
    return (iCaretPos);
}

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

Unable to open new window on iOS devices using $window.open

alertPopup.then (function(res) { if(ionic.Platform.isAndroid()) { $window.open('android_link_here', '_system') } else if(ionic.Platform.isIOS()) { $window.open('ios_link_here', '_system& ...

Selecting the next element in the DOM using Javascript

Here is the structure of my current setup: <div class="wrapper"> <div class="first"> <a class="button" href="">click</a> </div> <div class="second"> <div class="third"> S ...

What sets apart toBeInTheDocument from getBy* in @testing-library/react?

Can you distinguish between these two methods in react-testing-library? expect(screen.queryByText('<something>')).toBeInTheDocument(); And screen.getByText('<something>'); (The specific getBy* and queryBy* operation are no ...

Guide on filling accordion with data from Firebase

I have been working on a web page that retrieves data from my Firestore collection and is supposed to display each document with its corresponding fields. The goal is to populate the accordion with data from Firebase, but unfortunately, nothing is showing ...

React dynamic dropdown selection based on previous dropdown values

I have implemented 3 react input fields that are populating data to a useState Hook <FormControl fullWidth> <InputLabel>Primary Goal</InputLabel> <Select ...

Receiving an error when attempting to utilize a value from the .env file in createSecretKey function

Currently, my code looks like this: const secretKey = crypto.createSecretKey( Buffer.from(process.env.SECRET, "hex") ); However, I am encountering the following error message: "The value of 'key.byteLength' is out of range. It must be > ...

Enhance your viewing experience with the Zoom feature that activates when

I recently noticed on that I am able to zoom/enlarge a photo by clicking on it. Is there a way for me to incorporate this feature without purchasing the entire theme? While I understand the theme is designed for purchase, I only need this specific functi ...

Ways to personalize Angular's toaster notifications

I am currently utilizing angular-file-upload for batch file uploads, where I match file names to properties in a database. The structure of the files should follow this format: 01-1998 VRF RD678.pdf VRF represents the pipeline name RD represents the lo ...

I'm having trouble inserting text into a three.js scene

I recently started working with three.js and I'm experimenting with some basic code. However, I keep encountering the same error message. I was under the impression that I added the object to the scene after using the loader.load function, so I'm ...

Reading JavaScript files using the HTML 5 File Reader

Currently, I am working on a feature that allows users to drag and drop a folder containing JavaScript files into an HTML5 page. Here is the code snippet for my implementation: $scope.files = []; //Establish dropzone var dropbox; dropbox = document.getEle ...

Exploring the properties and methods of a node.js module object through iteration

Looking to compile a comprehensive list of all the Properties and Methods associated with the os Node.js module. One possible method is: var os = require('os'); Object.keys(os); Object.getOwnPropertyNames(os); Given that the os module is an Obj ...

Is it possible to include a component in an HTML file when the constructor of the component needs a parameter?

Recently delving into the world of AngularJs has been a captivating experience for me. I am aiming to develop a component with a constructor that accepts a parameter of type string. However, when I try to declare the selector on the HTML file, the componen ...

Space between flex content and border increases on hover and focus effects

My code can be found at this link: https://jsfiddle.net/walshgiarrusso/dmp4c5f3/5/ Code Snippet in HTML <body onload="resize(); resizeEnd();"> <div style="margin: 0% 13.85%; width 72.3%; border-bottom:1px solid gray;"><spanstyle="visibilit ...

What causes fs to produce an error when routing to a new page, yet refreshing the page resolves the issue?

Concern: I have developed a NextJs application with 4 input fields, each connected to a predefined options list read in as a json file within the project. The user can select two fields and then proceed to a search page by clicking a button. From the sear ...

What is the process for saving information to a database with JavaScript?

I am currently utilizing the Google Maps API for address translation, primarily through the use of a geocoder. I am interested in saving these results to a local database for future reference, as there are limitations on the total number and frequency of ...

Display jqgrid with borders and insert extra headers text at the top of the grid

function generateTableWithText(){ $("#active_grid").jqGrid("exportToHtml",{ includeLabels : true, includeGroupHeader : true, includeFooter: true, autoPrint : true ...

Issue with Refresh Triggering Update, localStorage, useState, useEffect Combination

I want my app to execute the code inside the useEffect hook every 5 seconds, regardless of whether the page is refreshed or not. Currently, the code only runs when the page is refreshed and then remains inactive until the page is refreshed again. It seems ...

Looking for a way to connect a background image in Vue CLI?

When running the code below, I encounter an issue. The code runs properly but the images are not displaying and instead showing the URL as unknown. How can I fix this problem? The images definitely exist. <template> <div class="slider">< ...

Using AJAX asynchronously in JavaScript commands synchronization

After researching similar questions on SO without finding a satisfactory answer, I encountered an issue with synchronous AJAX calls in my HTML/JavaScript page. Mozilla has deprecated some functionality related to synchronous requests, making it necessary f ...

Sliding off the canvas - concealed navigation

I have implemented CSS to hide a menu on mobile: #filter-column { position:absolute; left:-400px; } However, I want the menu to slide in from the left when the user clicks a link, and everything else should be hidden. When the layer is closed, th ...