Troubleshooting: AngularJS numeric input restriction issue persists

On my HTML page, I have an input box that is bound to an ng-model and restricted to only accept numbers using a custom directive. I am unable to utilize the default HTML5 restrictions like type="number". The issue I'm facing is that if a non-digit character is entered twice (e.g., typing 123 followed by 'k' twice), the 'k' gets appended to the number resulting in '123k'. However, upon typing another key, the 'k' is automatically removed by the directive.

I need assistance in resolving the problem of non-numeric characters appearing when the same key is pressed multiple times.

Below is the code for the directive I am using:

angular.module('app').
directive('onlyDigits', function () {

return {
    restrict: 'A',
    require: '?ngModel',
    link: function (scope, element, attrs, ngModel) {
        if (!ngModel) return;
        ngModel.$parsers.unshift(function (inputValue) {
            var digits = inputValue.split('').filter(function (s) { return (!isNaN(s) && s !== ' '); }).join('');
            ngModel.$viewValue = digits;
            ngModel.$render();
            return digits;
        });
    }
};

});

Answer №1

This code snippet demonstrates how we can restrict input to numbers only within a directive:

app.directive('numbersOnly', function () {
    'use strict';
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                if (inputValue === undefined) {
                    return '';
                }
                var transformedInput = inputValue.replace(/[^0-9]/g, '');
                if (transformedInput !== inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }
                return transformedInput;
            });
        }
    };
});

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 disable background color for droppable element

For my project, I am working with two div boxes. My goal is to make it so that when I drag and drop box002 into another div box001, the background color of box001 should change to none. I have attempted to achieve this functionality using jQuery without s ...

Using AJAX to dynamically update a DIV when there are changes in the XML data

After dedicating the past four years to solving this problem intermittently, my brain is feeling the strain. I serve as a volunteer designer for a local community project involving a radio station. Our "On Air" module showcases the current and upcoming tr ...

Tips on how to showcase up to 200 characters from a string

<?php include ($_SERVER['DOCUMENT_ROOT'].'/header.php'); include ($_SERVER['DOCUMENT_ROOT'].'/adtop.php'); if(mysql_num_rows($deals) > 0){ while($row = mysql_fetch_assoc($deals)){ echo '<div id= ...

The rotation duplication feature in THREE.js is malfunctioning

I'm encountering a bug where I'm trying to synchronize the rotations of two objects by copying the Quaternion from one object and applying it to another. However, I'm having trouble getting the rotation to be applied to the second object. I ...

clearInterval() is ineffective

[please include image description][1]I am encountering the following code function fnIsOnScreen(img, repeats = 5, desc, wait = 2000) { let iCounter = 0; return new Promise((resolve, reject) => { console.log("Executing Click"); ...

Sorting DataTable columns based on date

My Django application is utilizing DataTable. While most features work well, the date sorting seems to be off. It sorts by string rather than by date. html: <script> $(document).ready(function () { $('.document-table'). ...

div sliding inside another div sliding

I have implemented a sliding content feature where you click on the menu at the top and the content below slides to the next "li". Interestingly, within the last link on the main menu titled "replacement filters," there is another sliding content embedded ...

What is the best way to symbolize a breadcrumb offspring?

In my table representation, the breadcrumb is shown as: <ol class="breadcrumb" data-sly-use.breadcrumb="myModel.js"> <output data-sly-unwrap data-sly-list="${breadcrumb}"> <li itemscope itemtype="http://data-vocabulary.org/ ...

Changing the value in a textbox by altering a select option involves adjusting the input based on the selected

Is there a way to update the input value when a new option is chosen from a select dropdown menu? Click here to view an image. The goal is to have a different number of image upload fields based on the selected ad package (e.g., free package has 0 images ...

Utilize Angular.js to effortlessly convert a string containing special characters and numbers into an array, and seamlessly display it using ng

I am a beginner in angular.js and I'm facing an issue with converting a string into an array and displaying it using ng-repeat. I found a custom filter from a stackoverflow question and here are the codes: JS: var app = angular.module('globalMo ...

How can you delete a specific class name from a chosen element in VueJs?

My Vue.js method is set up like this. In the changeRoute function, I am able to change the class name by using e.target.className = 'clicked';. However, I am facing difficulty when trying to remove that class name from other elements using pre.re ...

Tips on sending a list via @Input using Angular5

I was seeking guidance on how to pass a list through an input. In my parent component, I have the following: list: Hero[] = [{Id: 2, Name: "Sll"}, {Id: 3, Name: "Sldsadasd"}] and in the HTML: <app-add-hero list="{{list}}" hero={{hero}}></app-ad ...

What could be causing the delay in my scroll event with React Three Fiber?

While using React Three Fiber, I encountered an issue with a react component that generates a sprite which is supposed to remain constant in size regardless of camera zoom. Although the algorithm appears to be functioning correctly (the size does not chang ...

What sorcery does Facebook use to alter the URL without triggering a page reload?

Similar Question: How can I update window location without a reload and # hack? Facebook and Ajax What method does Facebook use to change the URL without reloading the page? In the past, Facebook utilized the hash (#) symbol to prevent the page f ...

Generating multiple arrays within a multidimensional array using Javascript in a dynamic way

I have a single variable called $arrayQuantity that holds a changing value. This value determines how many item arrays should be created within the $itemsContainer array when the page is loaded. For example: //In this example, I want to create 3 `item` ...

C# implementation of the btoa function from JavaScript

I am in need of assistance recoding a JavaScript function to C# that makes use of the btoa method to convert a string of Unicode characters into base64. The challenge lies in ensuring that the encoding used in both languages is identical, as currently, the ...

Issue with AngularJS: The console.log statement is not showing any output

I recently created a controller for a login page. Below is the controller code I wrote: var authApp = angular.module('loginApp', []) authApp.controller('LoginCtrl', ['$scope', '$location', 'loginFactory', ...

Xstream produced a JSON response for a collection of objects

Utilizing Xstream for generating JSON in my application. Utilizing JSON for ajax support as well. When attempting: xstream.alias(classAlias, jsonModel.getClass()); //Note classAlias="records" responseStream.println(xstream.toXML(jsonModel)); where j ...

Is it possible to combine onmouseover and onmousedown events in a web application?

This particular code functions correctly for the onMouseOver and onMouseOut events, although it seems to encounter issues with the onMouseDown event. Below is the HTML5 and JavaScript code that I have written. Any feedback on where I may be going wrong wou ...

Guide to utilizing a TypeScript declaration file for a different function

I'm a beginner in TS and I've created a definition file to specify the argument types for a function in another file. customFunctions.ts export default ({}) => { const myCustomFunction = ({ param1 }: { param1: string }) => { return ...