In Angular.js, there is a limitation with ng-keyup where event.preventDefault() cannot be utilized, and ng-keypress may have delays when updating the value for an

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>

Answer №1

Consider utilizing a prior value as a backup option. Additionally, keep in mind that $scope.myScore will become undefined if it is assigned a value that exceeds the allowed range specified by your input. Therefore, ensure to account for this scenario within your conditional statement.

Hope this helps!

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  $scope.limit = function(e) {
    console.log( $scope.prevScore,$scope.myScore)
    if ($scope.myScore === undefined){
      $scope.myScore = $scope.prevScore
    }
    
    $scope.prevScore = $scope.myScore;
 }
 
 $scope.forInitialValue = function(e) {
    if ($scope.myScore === undefined){
      $scope.myScore = ""
    }
    
    $scope.prevScore = $scope.myScore;
 }
});
<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-change="limit($event)" ng-keydown="forInitialValue($event)"> {{myScore}}
</div>

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

Learn how to utilize Javascript to easily drag and drop an image within the same block

I am encountering an issue with dragging and dropping images or swapping them using JavaScript. I have tried to implement this in the code below, where clicking on icons moves them onto a colored div. However, I am now trying to drag and drop the images wi ...

a guide on retrieving FormData objects in PHP

Hey everyone, I have a question regarding a sample code snippet I posted here. In this code, I am successfully uploading a file using Ajax JQuery. However, I am struggling to figure out how to read the content of the uploaded file in my PHP code. Can anyon ...

With the use of discreet JavaScript, the parameter is not empty; instead, it contains values

Previously, my JavaScript code was functioning correctly when it was within the same page as my cshtml file: function SaveEntity() { // more code here alert(entity.FirstName); /* this shows that entity's properties have values */ $.post( ...

Determine the value of an array element based on a specified

I am in the process of creating an array, currently consisting of a single object that is computed based on other objects from a JSON file. Sampling my code // Retrieve JSON data and convert it to an object let myFile = '{"foo": {"bar": "baz"}, "thu ...

Utilize Ajax to load an Ajax-driven page

Currently, I am in the process of developing a GreaseMonkey script for the ServiceNow CMS that includes jQuery/AJAX. The main purpose of this script is to retrieve the number of incidents using the filter option provided by ServiceNow for technicians throu ...

Learn the best practices for incorporating jQuery and other JavaScript libraries in your Angular2 projects

Is it possible to integrate a demo showcasing Bootstrap carousel with CSS3 animations in Angular2 using HTML, CSS, and JS? I have created my own implementation in Plunker with Angular2, but I am facing issues with the animated inner content of the carousel ...

Tips for expanding frisby.js by adding new "expect" functionalities?

Looking to enhance the Frisby.js module with custom expect methods without altering the source code. These extensions are tailored for my REST API to streamline common tests into a single method. An issue arises as the Frisby.js module exports its methods ...

inability to conceal a two-dimensional marker array within Google Maps API v3

I need some help with my marker that refuses to hide Even after using setMap, my marker is still visible on the map Here is the error message from the console Please assist! Thank you in advance markers[i][j].setMap(null); markers.setMap(null); va ...

What is the process for assigning a value to the body in a div element?

Within a div, there is a body element structured like this: <div id = "TextBox1"> <iframe id = "TextBox1_1"> #document <html> <head></head> <body></body> </html> </iframe> </div> I have attempte ...

When utilizing jQuery and Ajax for form submission, PHP is unable to retrieve any data

I'm encountering an issue when trying to submit a form with only a radiobutton group named radiob. The script I am using for submitting the data is as follows: <script type="text/javascript"> $(function() { $("#myForm").submit(funct ...

Guide to configuring a service worker to manage the main website path

My website is hosted at https://xxxxxx.com. I have set the scope of the service worker file sw.js to /, but it seems that the service worker is unable to control the page https://xxxxxx.com. However, it can control other pages like https://xxxxxx.com/, e ...

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...

Ways to retrieve child state in React?

After creating my own form component with a render() method that looks like this: render() { return ( <form onSubmit={this.onSubmit} ref={(c)=>this._form=c}> {this.props.children} </form> ) } I enabled ...

The Ng-View feature is failing to provide the expected output, instead generating an error message stating "RangeError: Maximum call stack size exceeded

Having trouble with Ng-View not displaying the output correctly. When attempting to route from one page to another, I keep encountering the error message: "RangeError: Maximum call stack size exceeded" Please review the following code and provide sugge ...

Can the ThreeJS element be seen?

I am facing a challenge in my ThreeJS application where the view automatically centers on an object if it is close to the center of the view and closer than a specified distance. While I have information about the latitude and longitude of all objects and ...

Discover the location by determining the distance from established points

Before I get redirected to this particular question, let me clarify that while I've come across it, I am unable to comprehend its content (I wish I could). What I'm really seeking is a straightforward method (bearing in mind my limited math skill ...

Animating text so it moves to a random spot within a circular div

I hope everyone is doing well. For my assignment, I need to animate an image to a circular div container at a random location. Currently, I have already completed this task. You can view my work here: jsfiddle.net/f4p6b/137 However, the issue I am faci ...

How can one determine if a new document was created by Mongoose's upsert feature?

My code in node.js/express.js looks like this: var User = mongoose.model('User'); var usersRouter = express.Router(); usersRouter.put('/:id', function(req, res) { req.body._id = req.params.id; var usr = new User(req.body); ...

What is the best way to generate a hyperlink that will open a raphael graph in my own browser?

If I have a web page that includes a raphael.js drawing in <div id='my-canvas'></div> <body> <div id='part_one'>...</div> <div id='my-canvas'></div> <div id='part_thre ...

Perpetual duplication of data occurs upon inserting an item into the Array state of a React component

Whenever a new item is added to the React JS Array state, data duplication occurs. console.log(newData) The above code outputs a single object, but when you print the actual data with console.log(data) You will notice continuous duplicates of the same da ...