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.
Basically keypress events are fired before accepting the current value. So when you press on any key, keypress event is subscribed but you don't get the updated value/result for the recently pressed key. So, to get the last pressed key we can use the fromCharCode method and concat it with the value we got from the textbox. That's it,
HTML :
jQuery :
jsFiddle
It is bad UI to disable the input if a user inputs a bad value. I'm assuming you simply want to put a max value that the user cannot go over. If so, you can either clamp the value, or use the
max
attribute in your markup:If you input an invalid value, the input will turn red, and you cannot submit the form.
In response to Popnoodles answer above,
It is considered a good practice to use the type-safe equality operators === and !== instead of their regular counterparts == and != as in Javascript it can/may cause unexpected type coercions. So it should be
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.
http://jsfiddle.net/wvye2u0t/
Here's a solution for those using modern vanilla Javascript:
Just snap the value back down to the max when the user focuses away from the input.
You would set the input to a number type and the max value
and then add a function to the
onblur
method of the elementYou can also use
oninput
instead ofonblur
but that may cause the user to have to fight the input in certain situations.Example