Wim Mertens Wim Mertens - 1 year ago 62
jQuery Question

Get today's day and month in 2 digit format on click

I've got 3 date fields and a link to get today's date. It's all working fine but day and month default to single digits if less than 10, in FIREFOX. 1 September displays as 1 9 but I'd like it to display as 01 09. I have tried using jquery slice as explained in this post: How do I get Month and Date of JavaScript in 2 digit format?

But it is not working. Can someone point me in the right direction as to what I am doing wrong?

My code:

<div class="input-holder date-fields">
<input type="number" pattern="[0-9]*" inputmode="numeric" min="1" max="31" id="dd" class="dd" placeholder="DD" maxlength="2" />
<input type="number" pattern="[0-9]*" inputmode="numeric" min="1" max="12" id="mm" class="mm" placeholder="MM" maxlength="2" />
<input type="number" pattern="[0-9]*" inputmode="numeric" min="1900" id="yyyy" class="yyyy" placeholder="YYYY" maxlength="4" />
<a class="pick-today">Today</a>

and jquery:

$("a.pick-today").on("click", function (event) {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);

var now2 = new Date();
var month = ("0" + (now2.getMonth() + 1)).slice(-2);

var now3 = new Date();
var year = now3.getFullYear();

fiddle: https://jsfiddle.net/82a6671r/

UPDATE: it's working in Chrome but not in Firefox. Does anyone know why?

Answer Source

According to this bug, FF strips leading zeroes from numeric input fields.

Setting an input's value to "003" would display "3" in the input window, despite storing the value internally as "003".

Removing the field type will bypass this, though you should be cognizant of any effects this may cause when querying the field later. You may need parseInt.

Here's a fiddle that works on FF.

function leftPad(num, length) {
  var result = '' + num;
  while (result.length < length) {
    result = '0' + result;
  return result;

$("a.pick-today").on("click", function (event) {
  var now = new Date();
  var day = leftPad(now.getDate(), 2);
  var month = leftPad(now.getMonth() + 1, 2);
  var year = now.getFullYear();  
  var parent = $(this).parent('.input-holder');

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download