Skip to content
Home » How to Check and Limit Maximum Input Number in JavaScript Program

How to Check and Limit Maximum Input Number in JavaScript Program

This program demonstrates how to check and limit the maximum input number in a JavaScript program. It prevents users from entering numbers greater than 100 and disables the ability to use the delete and backspace keys to remove the entry. This functionality can be useful in scenarios where you want to restrict input values within a specific range.

Code

		checkMaxNumber(event) {
			if(event.target) {
				// document.querySelector('.maxNum').addEventListener('keydown',function (e) {
						if (event.target.value > 100 
						&& event.keyCode !== 46 // keycode for delete
						&& event.keyCode !== 8 // keycode for backspace
						) {
							event.preventDefault();
							event.target.value = 100;
					}
				// })
			}
		},

Code Explanation

The provided code snippet contains a function called “checkMaxNumber” that takes an event object as a parameter. The function is triggered whenever a user interacts with an input field.

Inside the function, there is an if statement that checks if the event target exists. This ensures that the code only executes if the event is triggered by an actual element on the page.

Within the if statement, there is a nested if statement that checks if the entered value is greater than 100 and if the event keycode is neither for delete (46) nor backspace (8). This condition is used to prevent the user from entering values above 100 and to disable the ability to delete the entry using the delete or backspace keys.

If the condition is met, the preventDefault() function is called to stop the default behavior of the event, which would be to accept the input. Additionally, the value of the input field is set to 100 to enforce the limit.

Here’s an example to illustrate how this code works:

html
<input type="text" class="maxNum" onkeydown="checkMaxNumber(event)">

In the above example, the “maxNum” class is added to the input element, and the “onkeydown” attribute is set to call the “checkMaxNumber” function with the event object. Whenever a key is pressed, the function will be triggered and limit the input value accordingly.

Conclusion

By using the provided code snippet, you can easily check and limit the maximum input number in a JavaScript program. This can be useful in various scenarios where you want to control the range of valid input values. Incorporate this functionality into your projects to enhance user experience and data validation. Remember to test and customize the code based on your specific requirements.

Also checkout the following codes.


Program to Use Firebase Messaging in JavaScript
How to Extract the Last 3 Characters from a String in JavaScript