Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  48] [ 3]  / answers: 1 / hits: 61098  / 10 Years ago, tue, june 17, 2014, 12:00:00

I'd like the user to be blocked from typing more if the value is over 100. So far I have the following from reading different posts:



$('.equipCatValidation').keyup(function(e){
if ($(this).val() > 100) {
e.preventDefault();
}
});


To confirm I want the value not the string length, and it can't be above 100.



However this is not preventing further input in the field. What am I missing.


More From » jquery

 Answers
3

Checking keyup is too late, the event of adding the character has already happened. You need to use keydown. But you also want to make sure the value isn't > 100 so you do need to also use keyup to allow js to check the value then too.


You also have to allow people to delete the value, otherwise, once it's > 100 nothing can be changed.


<input class="equipCatValidation" type="number" />

When using input type="number", change also needs to be on the event list.


$('.equipCatValidation').on('keydown keyup change', function(e){
if ($(this).val() > 100
&& e.keyCode !== 46 // keycode for delete
&& e.keyCode !== 8 // keycode for backspace
) {
e.preventDefault();
$(this).val(100);
}
});

http://jsfiddle.net/c8Lsvzdk/


[#70534] Sunday, June 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
;