Issue: The input type number with min and max constraints is not being enforced while typing in the input box. It allows values outside of the specified range to be entered. However, using the arrow buttons of the input type number works fine.
Solution Needed: The requirement is to restrict the user from entering values in the input type number that fall outside the specified min and max range without adding an extra directive or converting the input type to text.
"I am looking for a solution using Angular.js that addresses this issue by utilizing ng-keyup instead of ng-keypress with event.preventDefault() to prevent users from entering invalid values." Plunker
ng-keyup: Why am I unable to use event.preventDefault()? This is causing the ability to enter more/less than the specified min or max value. However, the correct value is obtained when manually changing it.
ng-keypress: There is a lag of 1 value which causes the first value to be undefined, leading to the problem in my question. Despite this, event.preventDefault() can be used.
Should use: ng-keyup with event.preventDefault(); or ng-keypress with correct order
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myScore;
$scope.limit = function(event, myScore){
console.log(event, $scope.myScore, myScore);
// Insert your code here to ensure myScore falls within (min-max) range
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<!-- <input type="number" ng-model="myScore" min="0" max="200" ng-keypress="limit($event, myScore)"> -->
<input type="number" ng-model="myScore" min="0" max="200" ng-keyup="limit($event, myScore)">
{{myScore}}
</div>