SoFunction
Updated on 2025-04-07

Javascript controls input time format

This article describes the method of Javascript controlling the input time format. Share it for your reference. The specific analysis is as follows:

I used to make a Javascript input to control the time format, mainly using the keydown and keyup events, but I felt that the writing was very complicated and there were bugs.

Today I learned about the difference between keypress events and keydown and keyup. It's roughly as follows (just know so much at the moment):

keydown:It is triggered when the key is pressed. Through event, you can get the keyCode and get the value before input into the text box;

keyup:It is triggered when the key is popped up (release). The keyCode can be obtained through event and the value after input from the text box can be obtained;

keypress:This event is basically the same in Chrome and IE, but Firefox is a little different;

1. In Chrome and IE: As long as the key pressed can appear characters in the text box, it will be triggered (such as input letters, numbers, symbols, etc.), the keyCode can be obtained through event, which is undefined; if characters cannot appear, it will not be triggered (such as arrow keys, Home, Backspace, etc.)

2. In Firefox: keys such as letters, numbers, symbols, directions, backspaces, etc. can all be triggered. You can get the key name. If the key pressed can output characters, it is 0. If the characters cannot be output, it is the corresponding ASCII code.

Going back to the topic, look at the code first (the event mentioned above is equivalent to the e in the following code):

Copy the codeThe code is as follows:
var isFF = /firefox/();
$("input").on({
    keyup : function (e) {
        !/^[\d:]+$/.test() && ( = "");
    },
    keypress : function (e) {
        if (isFF && !== 0) {
/// Pressing any key in Firefox will trigger the keypress event, while in IE/Chrome, only if the key that can output characters is pressed will trigger
/// For Firefox, !==0 presses one of the backspace, direction, Home and other buttons
        } else {
            if ( > 7)
                return false;
            if (/\d{2}$/.test()) {
                += ':';
            }
            var char = ( === 0 ? : );
            if (!/^\d/.test(char))
                return false;
        }
    }
});

IsFF && !== 0 is used to distinguish between keys that can output characters from keys that cannot output characters. Since values ​​may not be obtained in Firefox, it is used instead.

Keyup is used to deal with the problem of being able to enter Chinese or letters when using the input method.

The characters corresponding to the ASCII code are obtained through ().

I hope this article will be helpful to everyone's JavaScript programming.