Prevent user from typing in input at max value
Maybe keydown
instead of keyup
?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
$('.equipCatValidation').keydown(function(e){
if ($(this).val() > 100) {
e.preventDefault();
}
});
})
</script>
</head>
<body>
<input type="text" class="equipCatValidation">
</body>
</html>
EDIT: There is a valid comment here - Prevent user from typing in input at max value - to circumvent that you should probably store the previous value and restore it when necessary.
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/
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 :
<input id="inputBox" type="text" />
jQuery :
$("#inputBox").on("keypress", function(e){
var currentValue = String.fromCharCode(e.which);
var finalValue = $(this).val() + currentValue;
if(finalValue > 100){
e.preventDefault();
}
});
jsFiddle