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

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

    I spent some time working on the solution that Chris posted above and am accounting for everything except pasting, which isn't a requirement from the original poster as I read it.

    //Bind keyup/keydown to the input
    $('.date').bind('keyup', 'keydown', function(e) {
      //check for numerics
      var thisValue = $(this).val();
      thisValue = thisValue.replace(/[^0-9\//]/g, '');
      //get new value without letters
      $(this).val(thisValue);
      thisValue = $(this).val();
      var numChars = thisValue.length;
      $('#keyCount').html(numChars);
      var thisLen = thisValue.length - 1;
      var thisCharCode = thisValue.charCodeAt(thisLen);
      $('#keyP').html(thisCharCode);
      //To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
      if (e.which !== 8) {
        if (numChars === 2) {
          if (thisCharCode == 47) {
            var thisV = '0' + thisValue;
            $(this).val(thisV);
          } else {
            thisValue += '/';
            $(this).val(thisValue);
          }
        }
        if (numChars === 5) {
          if (thisCharCode == 47) {
            var a = thisValue;
            var position = 3;
            var output = [a.slice(0, position), '0', a.slice(position)].join('');
            $(this).val(output);
          } else {
            thisValue += '/';
            $(this).val(thisValue);
          }
        }
        if (numChars > 10) {
          var output2 = thisValue.slice(0, 10);
          $(this).val(output2);
        }
      }
    });
    $('.date').blur(function() {
      var thisValue = $(this).val();
      var numChars = thisValue.length;
      if (numChars < 10) {
        $(this).addClass('brdErr');
        $('#dateErr1').slideDown('fast');
        $(this).select();
      } else {
        $(this).removeClass('brdErr');
        $('#dateErr1').hide();
      }
    });
    

    There is a lot added and a CSS class for an error message for invalid dates.

    JSFiddle Here

提交回复
热议问题