Dynamic date mask when entering date

Is there a way in javascript or jQuery for dynamically detecting and changing when entering a date, both for entering a key and for copying and pasting into a text field?

I am trying to create a functional text field that has two digits, for example, a month.

Since the month can be a number from 1 to 12, I want the first digit to be 1 or 0.

However, the trick I'm trying to do is when the text field first gets focus, and the user asks for a number if this number is 2 - 9. I want the zero to automatically fill the first place, and then, but 9 in the second place.

Before I print anything, this date entry will look like this:

__/__/_____ 

If I Type "1"

 1_/__/_____ 

If I type "2", you should get

 02/__/_____ 

If I type "22" you should get

 02/2_/_____ 

If I type "77" you should get

 07/07/_____ 

I would be very interested in returning with a code or a link to a tool that is already doing this or a link to a previous post?

In the end I want to put it in a disguised form, so that 7/7/2011 or 7/7/11 or 07/07/2011 will be filled before 07/07/2011. In the final final version, I try to get the default year of the current decade, but you have a drop to every 10 years ++ -.

+6
source share
3 answers

Why not attach a listener to blur the text field, and not to the user.

Think about the user experience if you typed “1,” and suddenly, the input started adding or removing zeros to what you did when you did it?

 var dayInput = document.getElementById("day-input"); // usually, I'd just use event-listeners, but feel free to refactor dayInput.onblur = handleDayOrMonth; function handleDayOrMonth () { var el = (this === window) ? event.srcElement : this, number_string = el.value; // checking that it an actual number if (!isNaN(parseInt(number_string)) { if (number_string.length === 1) { el.value = "0" + number_string; } } } 

Work with the year will be the same, except that you add "20" to the beginning of what is.

Feel free to jQuery.

+2
source

I believe the functionality you want is provided by the jQuery Masked Input plugin

Demo: http://jsfiddle.net/SO_AMK/SEXAj/

Please note that it also only accepts numeric characters.

+2
source

The answer goes here ... jQuery is a hidden input plugin .

0
source

Source: https://habr.com/ru/post/920904/


All Articles