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

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

    Handles backspace, delete, paste, long press.

    let $jqDate = $('.date-slashes');
    
    $jqDate.bind('keyup', function(ev) {
      if (ev.which !== 8) {
        let input = $jqDate.val();
        let out = input.replace(/\D/g, '');
        let len = out.length;
    
        if (len > 1 && len < 4) {
          out = out.substring(0, 2) + '/' + out.substring(2, 3);
        } else if (len >= 4) {
          out = out.substring(0, 2) + '/' + out.substring(2, 4) + '/' + out.substring(4, len);
          out = out.substring(0, 10)
        }
        $jqDate.val(out)
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <input name="dob" class="date-slashes" type="tel" maxlength="10" placeholder="mm/dd/yyyy">

    0 讨论(0)
  • 2020-12-06 05:12

    Here is an updated Jquery version. Just change #txtDate with your field ID

         $(document).ready(function() {
            $("#txtDate").keyup(function(){
                if ($(this).val().length == 2){
                    $(this).val($(this).val() + "/");
                }else if ($(this).val().length == 5){
                    $(this).val($(this).val() + "/");
                }
            });
           });
    

    Source: https://forum.jquery.com/topic/auto-slash-in-date-field

    0 讨论(0)
  • 2020-12-06 05:14
    // This solution also handle the delete and backspace keys:
    
    jQuery('input[name="dateofbirth"]').bind('keyup',function(event){
        var key = event.keyCode || event.charCode;
        if (key == 8 || key == 46) return false;
        var strokes = $(this).val().length;
    
        if (strokes === 2 || strokes === 5){
            var thisVal = $(this).val();
            thisVal += '/';
            $(this).val(thisVal);
        }
        // if someone deletes the first slash and then types a number this handles it
        if (strokes>=3 && strokes<5){
            var thisVal = $(this).val();
            if (thisVal.charAt(2) !='/'){
                 var txt1 = thisVal.slice(0, 2) + "/" + thisVal.slice(2);
                 $(this).val(txt1);
            }
        }
        // if someone deletes the second slash and then types a number this handles it
        if (strokes>=6){
            var thisVal = $(this).val();
            if (thisVal.charAt(5) !='/'){
                var txt2 = thisVal.slice(0, 5) + "/" + thisVal.slice(5);
                 $(this).val(txt2);
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-06 05:15

    Try to use this plugin : http://digitalbush.com/projects/masked-input-plugin/ It works with jquery.

    0 讨论(0)
  • 2020-12-06 05:18

    My regex solution for React:

    // add auto "/" for date, i.e. MM/YY
      handleExpInput(e) {
    
        // ignore invalid input
        if (!/^\d{0,2}\/?\d{0,2}$/.test(e.target.value)) {
          return;
        }
    
        let input = e.target.value;
    
        if (/^\d{3,}$/.test(input)) {
          input = input.match(new RegExp('.{1,2}', 'g')).join('/');
        }
    
        this.setState({
          expDateShow: input,
        });
      }
    
    0 讨论(0)
  • 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):

    <input type="text" name="theDate" id="birthdate" maxlength="10"/>
    
    0 讨论(0)
提交回复
热议问题