Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript input validation using keypress, getting before and after values [duplicate]

Possible Duplicate:
keydown event new value

Didn't find that answer I was looking for, tried for a while, getting desperate:

My goal is to have a numeric non-negative input field that can be decimal and have a single character suffix that is a letter (legel suffix collection exists).

On a technical level - I need to be able to reject the input character, and I need both the values (before and after the input).

Approaches I Tried & Failed:

Keydown \ Keypress events:

cannot get the "after", just the before and the char/KeyCode. That's a problem since I don't know where to insert the new char in the old value (not neccessarily at the end..) - need a way to get the "after" or at least the index where the char belongs.

Keyup event:

Doesn't have the before value, but even worse - this doesn't fire when there's a long press ("00000000000000000...") and so I can't reject the input.

OnChange/change/blur - only fires on lose focus, not the functionality I need.

any ideas?

like image 233
EhudFisher Avatar asked May 01 '26 19:05

EhudFisher


1 Answers

How about a very brute method of saving the current value in a hidden field, and updating it when necessary? This will allow you to access the "before" and "after" states.

It's not a great approach but considering it's close to impossible to get the previous value, I would consider it.

like image 174
Nir Avatar answered May 04 '26 09:05

Nir