What's the best way to automatically insert slashes '/' in date fields

后端 未结 12 1526
执念已碎
执念已碎 2020-12-06 04:55

I\'m trying to add functionality to input date fields so as when the users enters in digits, slashes \"/\" get automatically added.

So suppose I have the following

12条回答
  •  悲&欢浪女
    2020-12-06 05:25

    If you're looking for pure js version of @Chris's answer

    var newInput = document.getElementById("theDate");
    newInput.addEventListener('keydown', function( e ){
        if(e.which !== 8) {
            var numChars = e.target.value.length;
            if(numChars === 2 || numChars === 5){
                var thisVal = e.target.value;
                thisVal += '/';
                e.target.value = thisVal;
            }
        }
    });
    

    And HTML section might be(if necessary):

    
    

提交回复
热议问题