Below is my code that prevents the user from typing more than 10 characters in an input box, as well as providing the user with information of how many characters that’s left.
The problem is that if the user is erasing what he’s typed (on or more characters), the number of characters isn’t updated.
So, my questions is: How can I detect if the user is erasing in the input box?
Thanks in advance!
$('.imageTitle').keypress(function(e) {
var value = $(this).val(),
valueLength = value.length,
set = 10,
remain = parseInt(set - valueLength);
if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
$('.imageTitle').val((value).substring(0, valueLength - 1))
}
$('#titleCharsLeft').html(' ' + remain);
});
If I am not mistaken You dont need any special mechanism to detect erasing You can do that with simple
$.keyup. Use the following code. It updates the remaining character like Twitter but you can modify it to count total characters too.Working Fiddle
It’s a generalized one which should get you started. Modify it to suit your need.
UPDATE
You can even add support for
inputevent on browsers which support it for events like paste, long keypress or drag. Like thisModified Fiddle to more suit your need.
Reference: oninput or this