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

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

    This solution works for me. I have captured the blur event though you will have to change the code if you want to use keyup event. HTML

    
    

    Javascript

    function bar(txtBox) {
      if (txtBox == null) {
        return ''
      }
    
      var re = new RegExp(/(\d{6})(\d{2})?/);
    
      if (re.test(txtBox.value)) {
        if (txtBox.value.length == 8) {
          txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 4) + '/' + txtBox.value.substring(4, 8)
        }
        if (txtBox.value.length == 7) {
          txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 3) + '/' + txtBox.value.substring(3, 8)
        }
    
        if (txtBox.value.length == 6) {
          if (txtBox.value.substring(4, 6) < 20) {
            txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 4) + '/20' + txtBox.value.substring(4, 6);
          } else {
            txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 4) + '/19' + txtBox.value.substring(4, 6);
          }
        }
      }
      return txtBox.value;
    }
    

提交回复
热议问题