Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

javascript - 在日期字段中自动插入斜杠“ /”的最佳方法是什么?(What's the best way to automatically insert slashes '/' in date fields)

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:(因此,假设我有以下html:) <input type="text" id="fooDate" /> And suppose I have the following javascript:(并假设我有以下javascript:) var dateField = document.getElementById("fooDate"); dateField.onkeyup = bar; What should bar be?(bar应该是什么?) So far the best google result was:(到目前为止,最好的google结果是:) 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(用它滚:p)   ask by Shawn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update/Edit: Obviously the most simple solution today with widespread HTML5 support is to use <input type="date" name="yourName"> .(更新/编辑:显然,当今具有最广泛的HTML5支持的最简单的解决方案是使用<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/(工作小提琴: https : //jsfiddle.net/ChrisCoray/hLkjhsce/)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...