1
<tr>
   <td><label>Birthdate</label>
      <input type="text" placeholder="mm/dd/yyyy" name="birthdate" maxlength="10"/>
   </td>
</tr>

Well, my code is working but I want my "input type text" to auto format like a date (html 5 input type=date) because in my Servlet I convert it to Age. The problem is that, if I use the "input type=date" the conversion is error so I decided to use "input type=text" and it's working. So is it possible to auto put "/" in this format "mm/dd/yyyy"? For example, if the user input 2 character an "/" will auto input etc.


Servlet for birthdate to Age

        String birthdate = request.getParameter("birthdate");


        int monthDOB = Integer.parseInt(birthdate.substring(0, 2));
        int dayDOB = Integer.parseInt(birthdate.substring(3, 5));
        int yearDOB = Integer.parseInt(birthdate.substring(6, 10));

        DateFormat dateFormat = new SimpleDateFormat("MM");
        java.util.Date date = new java.util.Date();
        int thisMonth = Integer.parseInt(dateFormat.format(date));

        dateFormat = new SimpleDateFormat("dd");
        date = new java.util.Date();
        int thisDay = Integer.parseInt(dateFormat.format(date));

        dateFormat = new SimpleDateFormat("YYYY");
        date = new java.util.Date();
        int thisYear = Integer.parseInt(dateFormat.format(date));

        int calAge = thisYear - yearDOB;

        if (thisMonth < monthDOB) {
            calAge = calAge - 1; 
        }

        if (thisMonth == monthDOB && thisDay < dayDOB) {
            calAge = calAge - 1;
        }

        String age = Integer.toString(calAge);

Update in the form

<tr>
    <td><label for="inputName">Birthdate</label>
       <input type="text" placeholder="mm/dd/yyyy" id="input_date" name="birthdate" maxlength="10"  />
    </td>
</tr>

Update in the source

<script src="../scripts/formatter.js"></script>
<script src="../scripts/formatter.min.js"></script>
<script src="../scripts/jquery.formatter.js"></script>
<script src="../scripts/jquery.formatter.min.js"></script>

Added Script

<script>
     $('#input_date').formatter({
       'pattern': '{{99}}/{{99}}/{{9999}}',
       'persistent': true
     });
</script>

I also tried the javascript but it's not working...

Ghost
  • 139
  • 1
  • 2
  • 10
  • and if possible, if an character a-z or somthing other than numbers will be disabled... – Ghost Oct 31 '13 at 14:46

4 Answers4

3

I've been watching a project on GitHub (and providing feedback to improve it) for just such kind of formatting called formatter.js http://firstopinion.github.io/formatter.js/demos.html This might be just the thing you're looking for.

This wouldn't stop you from typing in dates like the 53rd of May... but it will help you format.

new Formatter(document.getElementById('date-input'), {
  'pattern': '{{99}}/{{99}}/{{9999}}',
  'persistent': true
});

or

$('#date-input').formatter({
  'pattern': '{{99}}/{{99}}/{{9999}}',
  'persistent': true
});
scunliffe
  • 57,883
  • 24
  • 118
  • 156
  • I downloaded the file and put id="date-input" in the "input type=text", also added the script source and the answer inside script but it was not working. why is that? – Ghost Oct 31 '13 at 15:17
  • I'm not entirely sure... I'd likely need to see the code in action. – scunliffe Oct 31 '13 at 15:43
  • whichever JS code you use you should only need 1 JavaScript file... it looks like you are including multiple copies over and over. If you are trying to use the formater.js library you only need to include the minified version "formatter.min.js". Next you've added the code to apply the formatter in "jQuery style"... do you have jQuery already loaded... and if so what version (in case there is a conflict) – scunliffe Oct 31 '13 at 16:05
  • version... jQuery 2.0.3 – Ghost Oct 31 '13 at 16:19
2

I have an alternative that works with a jquery-ui datepicker, without formatter.js. It is intended to be called from the keyup and change events. It adds zero padding. It works with various supported date formats by constructing expressions from the dateFormat string. I can't think of a way to do it with fewer than three replaces.

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

Adam Leggett
  • 2,797
  • 23
  • 21
1

use datepicker api from jquery here is the link Datepicker

and here is the working code

<tr>
   <td><label>Birthdate</label>
      <input type="text" placeholder="mm/dd/yyyy" name="birthdate" id="birthdate" maxlength="10"/>
   </td>
</tr>

<script>
  $(function() {
    $( "#birthdate" ).datepicker();
  });
</script>

EDIT

$("input[name='birthdate']:first").keyup(function(e){
    var key=String.fromCharCode(e.keyCode);
    if(!(key>=0&&key<=9))$(this).val($(this).val().substr(0,$(this).val().length-1));
    var value=$(this).val();
    if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});

this is the code that you may need

here is the fiddled code

  • thanks but the datepicker, is set to the current date... so it's inconvenient because i'm using it on birthdate – Ghost Oct 31 '13 at 14:57
  • 2
    you can use jquery `.keyup()` function to auto put `/` after 2 characters –  Oct 31 '13 at 15:05
  • how? I saw it in the w3school but I saw different. can u give some codes – Ghost Oct 31 '13 at 15:11
  • 1
    code added in edit tag, first if condition check whether the entered value if between 0 and 9, if not, it will remove that value. second fragment consist of adding `/` after 2 and 4 characters. –  Oct 31 '13 at 15:25
  • 2
    @Ghost yes there was some glitches in last code, check now, edited and added fiddle too, u can check it there! –  Oct 31 '13 at 15:42
  • I already copied it but still not working, is there any onload? – Ghost Oct 31 '13 at 15:55
  • 2
    be sure to include latest version of jquery first by `` and then run it, check the fiddle link i provided, my code is working properly there –  Oct 31 '13 at 16:03
  • 2
    create a fiddle of your code on jsfiddle.net and save there and post link here and also make sure you hadn't used name="birthdate" anywhere else –  Oct 31 '13 at 16:25
  • 2
    you hadn't addes jquery in your code, go to pannel on left and add jquery 1.10.1 from 1st drop-down menu, run it again, wait for complete loading of page and then check, it is working perfectly. –  Oct 31 '13 at 16:39
  • 2
    and in your main code(in your local copy) add `` in the `` section or in the last of `` before using anyother script tag –  Oct 31 '13 at 16:40
  • it's already working... thankz, but in my localhost still not... i'll try to find the error or maybe the version of my jquery, it .2 – Ghost Oct 31 '13 at 16:48
  • 2
    for your localhost, download the jquery.js from http://code.jquery.com/jquery-1.10.2.min.js and save it as jquery.js in your local machine, and then add following code in your tag and then this will work fine –  Oct 31 '13 at 16:56
  • damn, I already did everything but still not working... damn it... the fiddle worked but why my localhost does not... s*** – Ghost Oct 31 '13 at 17:08
  • my head tag and I put the ur code inside the jquery but still not working – Ghost Oct 31 '13 at 17:09
  • 2
    make another fiddle and add your complete html file in just html window and ignore all warnings, run it, save it and give link to me –  Oct 31 '13 at 17:14
  • 2
    http://jsfiddle.net/qubdx/11/ and make sure your local machine is properly connected to internet –  Oct 31 '13 at 17:26
  • yah.. It's properly connected... So u don't know also the problem? – Ghost Oct 31 '13 at 17:33
  • 2
    yeah, i tried that in my localhost and it was working fine! use this html file and tell me http://jsfiddle.net/qubdx/12/ –  Oct 31 '13 at 17:37
  • @Ghost just as a standard, you can consider answer of optional optional for upvoting and accepting, if your problem is solved by it. rest depends on you –  Oct 31 '13 at 18:07
  • @lessinfo my rep is still not enough to upvote, i'll upvote it in the future – Ghost Nov 01 '13 at 15:52
  • I posted an answer below that also works with `keyup` (as well as `change`). It handles paste, select all, single digit months and days, etc. https://jsfiddle.net/4msunL6k/ – Adam Leggett Feb 04 '16 at 20:05
  • doesn't work with autofill on safari – tony Jan 27 '21 at 03:49
0

user2897690 had the right idea but it didn't accept Numpad numbers. So took their javascript and modified it to work.

Here is my interpretation of their code with the added feature.

$("input[name='birthdate']:first").keyup(function(e){
    var chars = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
    var key=chars.indexOf(e.keyCode);
    console.log(key);
    if(key==-1)$(this).val($(this).val().substr(0,$(this).val().length-1));
    var value=$(this).val();
    if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});
Matthew D Auld
  • 368
  • 1
  • 3
  • 16