在日期字段中自动插入斜杠'/'的最佳方法是什么? [英] What's the best way to automatically insert slashes '/' in date fields

查看:210
本文介绍了在日期字段中自动插入斜杠'/'的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为输入日期字段添加功能,以便当用户输入数字时,斜线/会自动添加。



所以假设我有以下html:

 < input type =textid =fooDate/> 

假设我有以下javascript:

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

bar 应该是什么?



到目前为止,最好的谷歌搜索结果是:

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

}

谢谢!



也是 - 我知道输入斜杠时会输入斜线。更新/编辑:显然,现在最广泛的HTML5支持的最简单解决方案是使用< input type =datename =yourName>



对于抱怨它没有容纳退格或粘贴,我修改了原文:

  //将输入DOM元素放入jQuery对象
var $ jqDate = jQuery('input [name =jqueryDate]');

//将keyup / keydown绑定到输入
$ jqDate.bind('keyup','keydown',函数(e){

// To我们检测哪个键被按下 - 如果退格,什么也不做:
if(e.which!== 8){
var numChars = $ jqDate.val()。length;
if(numChars === 2 || numChars === 5){
var thisVal = $ jqDate.val();
thisVal + ='/';
$ jqDate。 val(thisVal);
}
}
});

`



工作小提琴:


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 html:

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

And suppose I have the following javascript:

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

What should bar be?

So far the best google result was:

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 + '/';
    }

}

Thanks!

also -- I know having slashes being entered as you type sucks. Just roll with it :p

解决方案

Update/Edit: Obviously the most simple solution today with widespread HTML5 support is to use <input type="date" name="yourName">.

For those complaining that it doesn't accommodate backspaces or pasting, I modified the original:

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

`

Working Fiddle: https://jsfiddle.net/ChrisCoray/hLkjhsce/

这篇关于在日期字段中自动插入斜杠'/'的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆