Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 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:

<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

See Question&Answers more detail:os

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

1 Answer

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

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...