Issues have been reported with event listeners (specifically onkeypress and onkeydown) not functioning properly on Android's numeric keyboard

After countless hours of troubleshooting, I am convinced that something is awry.

My issue revolves around a simple input field:

<input type="number">

I intend for it to exclusively accept numbers (0-9) and nothing else. To accomplish this, I implemented an event listener to monitor the event's keycode.

While everything functions smoothly across most platforms, Android presents a challenge. The

type="number"

attribute triggers a numeric keyboard, which is beneficial, but also allows other characters like commas, dots, and hyphens. When one of these special characters is pressed, the behavior becomes erratic:

  • The onkeypress event fails to trigger at all (why?)
  • The onkeydown event fires, and the specified function executes. However, the browser has already inserted the character (why?), preventing the use of the preventDefault method on the event.
  • The input event fires as well, but the "code" and "which" properties of the event object are undefined. Once again, the browser has preemptively inputted the character.

What am I overlooking?

In my AngularJs-powered environment, I have configured event listeners within a directive. Unfortunately, replicating the process with jQuery doesn't resolve the issues.

Suggestions have been made to utilize "$parsers" to filter out unwanted characters and push only the desired values. Yet, this approach seems ineffective because the input type is "number," and the browser expects solely numerical inputs (implying an error in how Android browsers handle this).

For a demonstration, refer to this working Fiddle, ideally accessed on an Android device.

Answer №1

The event triggering the keypress doesn't seem to be working, leaving only keydown and keyup events to handle. When using onkeydown, it is possible to call on the preventDefault() method. However, the question arises - what exactly are we trying to prevent here? With charCode constantly set at 0 and keyCode at 229, thorough input validation becomes crucial.

Consider implementing a solution like the following:

if (!event.charCode) {
    this.removeInvalidChars();
    return;
}

private removeInvalidChars(): void {
    setTimeout(() => {
        let input = this.control.control.value;

        if (input) {
            input.split('').forEach((char: string) => {
                if (!this.pattern.test(char)) {
                    input = input.replace(char, '');
                }
            });
            this.control.control.setValue(input);
        }
    });
}

Answer №2

This custom directive utilizes $parsers.unshift to format input values:

app.directive('format', ['$filter', '$window', function($filter, $window) {
  return {
    require: '?ngModel',
    link: function(scope, elem, attrs, ctrl) {

      if (!ctrl) return;

      scope.plainNumber = scope.test+'';

      ctrl.$parsers.unshift(function(viewValue) {         

      if(!viewValue){
         viewValue = scope.plainNumber;
      }
        scope.plainNumber = viewValue.replace(/[^\d]/g, '');

        elem.val(scope.plainNumber);
        return scope.plainNumber;            
      });
    }
  };
}]); 

Example of usage:

<input type="number" ng-model="test" format /> 

View Demo on Fiddle


Tested successfully on Android devices

Answer №3

When using inputType="numberSigned", you will be limited to only receiving numbers between 0-9. In my experience with native Android, this feature works perfectly without any hiccups.

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

How can I implement long polling effectively with jQuery and AJAX?

Currently, I am working on a project that requires live notifications. I considered using socket.io, but due to time constraints, I decided to explore AJAX and jQuery as alternatives. I have outlined my code structure below and I am curious if this appro ...

The Angular $http module seems to be failing to transmit any data

Even though this issue has been resolved numerous times, I am still having trouble getting it to work. This is my js call: var data = { value: 7 }; $http.post('api/controller/method', data); However, in Fiddler there is no Content-Type and no ...

Issue: In Firefox, resizing elements using position:absolute does not work as expected

My resizable div code looks like this: #box { height: 10rem; width: 10rem; resize: both; overflow: hidden; border: solid black 0.5rem; position: absolute; pointer-events: none; } <div id="item"></div> While it works perfectly ...

Issue with Heroku: Unable to serve images through NodeJS Express server

I have an app deployed on Heroku that displays an image. app.js package.json package-lock.json public |__ image1.png |__ image2.png This is the code within app.js const express = require('express'); const app = express(); const path = re ...

What is the reason behind jshint issuing an alert specifically for the lastSelectedRow being

Upon pasting the code below into jshint.com, an error is generated: Read only in reference to line: lastSelectedRow = 1; I am curious as to why this error occurs and how it can be remedied. Interestingly, jslint does not return this error. /*global la ...

Align list items in the center horizontally regardless of the width

I have created this container element: export const Container = styled.section<ContainerProps>` display: flex; justify-content: center; `; The current setup is vertically centering three list items within the container. However, I am now looking ...

Tips for transferring data from a parent component to a child component in React?

Recently, I've been restructuring a small application that was initially confined to one file by breaking it into its own separate components. Right now, I have a child component called UsersTable which I am displaying within the parent component User ...

Exploring Meta Data Updates in a React Server-Side Rendering Application

I'm in the process of developing a react application and encountering some challenges... I've set up the server-side rendering of my page using this code snippet... const router = express.Router(); router.get('/homepage', (req, res) ...

Videos playing simultaneously

Can we synchronize the video playback on two computers simultaneously? If there is buffering on one computer, the other must pause and wait. ...

Show only relevant dropdown options when a radio button is selected, and also automatically adjust options when the page

I am working on a form that includes radio buttons and a dropdown list. If the user chooses 'girls', I need to display only caroms and chess, which are specified in the girlsGames variable. If the user selects boys, I want to show the dropdown ...

Discovering the property name of an object in Angular using $watch

Is there a way to monitor an object for changes in any of its properties, and retrieve the name of the property that changed (excluding newValue and oldValue)? Can this be accomplished? ...

What is the best method for preserving HTML content using Ajax?

I am having difficulty storing HTML code in a database using AJAX. Despite having the correct connection information, I am unable to write to the table. <div id="others"> <div id="name"><input type="text" name="results" class="name"> ...

Is there a definitive way to distinguish between scrollTop and scrollHeight in web development?

For instance, function checkingScroll(){ var newHeight = element.scrollHeight; var scrollTopValue = element.scrollTop; alert("The scrollHeight property is: " + newHeight + "px"); alert("The scrollTop property is: " + scrollTopValue ...

I'm trying to find the official documentation for the Mongoose save() method. Can

When it comes to working with Mongoose, saving data is a common task. However, the official documentation for the save method seems to be elusive. A quick Google search brings up: https://mongoosejs.com/docs/models.html and https://mongoosejs.com/docs/d ...

Having trouble with angular.fromJson parsing a local JSON file?

I am currently trying to parse a local json file (data.json) using angular.fromJson, but I am not very familiar with this process. I came across a helpful post on How do I update/add to a json file that I have been following. The issue I am facing is that ...

Tips for sending information to a modal window

I need to transfer the userName from a selected user in a list of userNames that a logged-in user clicks on to a twitter bootstrap modal. I am working with grails and angularjs, where data is populated using angularjs. Set-Up The view page in my grails a ...

Error unfound: [CLIENT_MISSING_INTENTS]: The Client requires valid intents to function properly

I've gone through multiple tutorials, but I keep encountering an uncaught TypeError. Despite following the suggested solutions, the error persists. I even tried implementing the "intent" solution, but it's prompting a change in "const client = ne ...

Why does JavaScript not wait for the completion of forEach and instead executes the next line immediately?

While creating my api in nodejs and attempting to push the mongoose return count to a newly created array, it does not wait for the forEach loop to finish before executing json.res() and returning a null response. However, when I use setTimeout(), the re ...

Implementing data binding with rxjs and Angular 1.6: A step-by-step guide

I've been attempting to fetch data using rxjs from a promise method, and when it is successful, I subscribe to it and pass it to my scope. Although I can see the response object attached to my scope, it doesn't seem to be mapping in the UI. Her ...

Retrieve the value of an AngularJS expression and display it in a window alert using AngularJS

Hey there, I am in the process of trying to display the value of an expression using AngularJs As a beginner in angular, I am working on figuring out how to retrieve the value of the expression either with an alert or in the console. I'm utilizing A ...