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

后端 未结 12 1513
执念已碎
执念已碎 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)
      }
    });
    
    

提交回复
热议问题