在日期字段中自动插入斜杠“/”的最佳方法是什么

时间:2011-02-15 15:48:37

标签: javascript html

我正在尝试添加输入日期字段的功能,以便当用户输入数字时,斜杠“/”会自动添加。

假设我有以下html:

<input type="text" id="fooDate" />

假设我有以下javascript:

var dateField = document.getElementById("fooDate");
dateField.onkeyup = bar;

bar应该是什么?

到目前为止,谷歌的最佳结果是:

function bar(evt)
{
    var v = this.value;
    if (v.match(/^\d{2}$/) !== null) {
        this.value = v + '/';
    } else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
        this.value = v + '/';
    }

}

谢谢!

也 - 我知道在你打字的时候输入斜线。只需滚动它:p

13 个答案:

答案 0 :(得分:18)

更新/编辑:显然,目前支持广泛HTML5的最简单的解决方案是使用<input type="date" name="yourName">

对于抱怨它不能容纳退格或粘贴的人,我修改了原文:

//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);
        }
  }
});

`

工作小提琴:https://jsfiddle.net/ChrisCoray/hLkjhsce/

答案 1 :(得分:4)

这是一种简单的方法:

&#13;
&#13;
Date: <input name=x size=10 maxlength=10  onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')">
&#13;
&#13;
&#13;

Here ia a fiddle : https://jsfiddle.net/y6mnpc1j/

答案 2 :(得分:2)

我有一个可以使用jquery-ui datepicker的替代方法,没有formatter.js。它旨在从keyupchange事件中调用。它增加了零填充。它通过从dateFormat字符串构造表达式,使用各种支持的日期格式。我只能用少于三次的替换来想办法。

// Example: mm/dd/yy or yy-mm-dd
var format = $(".ui-datepicker").datepicker("option", "dateFormat");

var match = new RegExp(format
    .replace(/(\w+)\W(\w+)\W(\w+)/, "^\\s*($1)\\W*($2)?\\W*($3)?([0-9]*).*")
    .replace(/mm|dd/g, "\\d{2}")
    .replace(/yy/g, "\\d{4}"));
var replace = "$1/$2/$3$4"
    .replace(/\//g, format.match(/\W/));

function doFormat(target)
{
    target.value = target.value
        .replace(/(^|\W)(?=\d\W)/g, "$10")   // padding
        .replace(match, replace)             // fields
        .replace(/(\W)+/g, "$1");            // remove repeats
}

https://jsfiddle.net/4msunL6k/

答案 3 :(得分:1)

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);
        }
    }

});

答案 4 :(得分:1)

如果您正在寻找@ Chris的答案的纯js版本

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;
        }
    }
});

HTML部分可能(如有必要):

<input type="text" name="theDate" id="birthdate" maxlength="10"/>

答案 5 :(得分:1)

处理退格键,删除,粘贴,长按。

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">

答案 6 :(得分:1)

我的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,
    });
  }

答案 7 :(得分:0)

尝试使用此插件:http://digitalbush.com/projects/masked-input-plugin/ 它适用于jquery。

答案 8 :(得分:0)

此解决方案适合我。我已捕获模糊事件,但如果要使用keyup事件,则必须更改代码。 HTML

<input type="text" id="fooDate" onblur="bar(this)"/>

的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;
}

答案 9 :(得分:0)

我花了一些时间来研究Chris在上面发布的解决方案,并负责除粘贴之外的所有工作,这在我阅读原始海报时不是必需的。

//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();
  }
});

添加了很多内容,并提供了CSS类来显示无效日期的错误消息。

JSFiddle Here

答案 10 :(得分:0)

对于有反应的用户,他们想要在将日期同步到状态之前对日期执行操作,可以执行以下操作:

onChangeText={(text) => {
   // Format the value and remove slashes, so addItemEvery will work
   let value = text.replace(/\/+/g, "");
   // We substring to add / to only the first part, every two characters
   const firstFourChars = addItemEvery(value.substring(0, 5), "/", 2);
   value = firstFourChars + value.substring(5, value.length);


   ... e.g. update state
}

...

function addItemEvery(str, item, every) {
  for (let i = 0; i < str.length; i++) {
     if (!(i % (every + 1))) {
        str = str.substring(0, i) + item + str.substring(i);
     }
  }

  return str.substring(1);
}

答案 11 :(得分:0)

<SCRIPT LANGUAGE="JavaScript">
    function addSlashes(f)
    {
        f.value = f.value.slice(0,2)+"/"+f.value.slice(2,4)+"/"+f.value.slice(4,7);
    }
</SCRIPT>

答案 12 :(得分:-1)

这里是Jquery的更新版本。只需使用您的字段ID更改#txtDate

     $(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() + "/");
            }
        });
       });

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