Skip to content
Advertisement

Insert “/” in MM/YYYY textbox on keypress event

I want to enter a “/” when user enters MM(2 digit) so it will be like MM/YYYY.

I have done similar for credit card number input which insert a space after 4 digit on keypress.

JavaScript

Advertisement

Answer

Fiddle

This works with

  • Regular keyboard input
  • Copy/Cut/Paste
  • Selected text

Adding the /

Because you’re programmatically adding the / character, you have to update the cursor position whenever that affects the new input value. This can be more than one character if the user is pasting something. Most of the code complexity revolves around this issue.

There are a lot of comments in the code explaining the various situations that come up because of the /.

Full Code

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement