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

后端 未结 12 1543
执念已碎
执念已碎 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:02

    Update/Edit: Obviously the most simple solution today with widespread HTML5 support is to use .

    For those complaining that it doesn't accommodate backspaces or pasting, I modified the original:

    //Put our input DOM element into a jQuery Object
    var $jqDate = jQuery('input[name="jqueryDate"]');
    
    //Bind keyup/keydown to the input
    $jqDate.bind('keyup','keydown', function(e){
    
      //To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
        if(e.which !== 8) { 
            var numChars = $jqDate.val().length;
            if(numChars === 2 || numChars === 5){
                var thisVal = $jqDate.val();
                thisVal += '/';
                $jqDate.val(thisVal);
            }
      }
    });
    

    `

    Working Fiddle: https://jsfiddle.net/ChrisCoray/hLkjhsce/

提交回复
热议问题