2

I am using jQuery DatePicker in my web application, but I want to use the native type="date", when the application is being used on iOS so it uses the native date picker in iOS safari instead.

The main point being that I do not want users to loose out on functionality, regardless of their device, however I am not happy with jQuery DatePicker on iOS as it is clunkly to use and occasionally messes up the design of the application.

If I use the type="date" then the way it is written at the moment, I have both the jQuery DatePicker showing up, as well as the native iOS function for dates.

Basically what is required is some sort of detection for the support of type="date", however it would seem that this is rather lacking, as some browsers will claim support for date types but this does not necessarily mean that they offer a UI for dates.

P.S Does Android/Windows phone have a native function for type="date"?


Code Sample

<div class="col-xs-5 col-sm-4">
  <input type="date" class="form-control date-picker" id="formatD" name="formatD" placeholder="Enter date of format approval" value="<?php echo $app->getCurrentDate() ?>">
</div>

<script>
  $(function() {

    $( ".date-picker" ).datepicker({
      format: "dd/mm/yyyy"
    });

  });
</script>

Update

Found a good solution using Modernizr, see answer below.

Craig Lowe
  • 83
  • 1
  • 9

2 Answers2

1

You have to detect if the browser supports native input date, and If is not, call the date time picker js library. How can you detect the input date support?

Here in this question

Community
  • 1
  • 1
quindimildev
  • 1,280
  • 8
  • 21
  • Your analysis of the question is much better than I have written. I have looked at the other Q&A and it seems that there is no straight forward answer and it requires somewhat of a hack to build in support, which I'm never particularly happy with because you cannot tell when the hack will fail. Thank you for your help. – Craig Lowe Nov 12 '15 at 23:16
1

The main aspect of the solution is to detect what the browser is capable of, the easiest way I have found to do this is using Modernizr, I used a custom build with just the input types selected, as that is all I need.

This solution means that browsers without sufficient support for dates, more specifically, those that do not offer a UI fallback to the jQuery DatePicker, those that do support an input type date UI, use the native feature.

/*! modernizr 3.2.0 (Custom Build) | MIT *
 * http://modernizr.com/download/?-inputtypes !*/
!function(e,t,n){function a(e,t){return typeof e===t}function s(){var e,t,n,s,i,o,c;for(var u in r)if(r.hasOwnProperty(u)){if(e=[],t=r[u],t.name&&(e.push(t.name.toLowerCase()),t.options&&t.options.aliases&&t.options.aliases.length))for(n=0;n<t.options.aliases.length;n++)e.push(t.options.aliases[n].toLowerCase());for(s=a(t.fn,"function")?t.fn():t.fn,i=0;i<e.length;i++)o=e[i],c=o.split("."),1===c.length?Modernizr[c[0]]=s:(!Modernizr[c[0]]||Modernizr[c[0]]instanceof Boolean||(Modernizr[c[0]]=new Boolean(Modernizr[c[0]])),Modernizr[c[0]][c[1]]=s),l.push((s?"":"no-")+c.join("-"))}}function i(e){var t=u.className,n=Modernizr._config.classPrefix||"";if(f&&(t=t.baseVal),Modernizr._config.enableJSClass){var a=new RegExp("(^|\\s)"+n+"no-js(\\s|$)");t=t.replace(a,"$1"+n+"js$2")}Modernizr._config.enableClasses&&(t+=" "+n+e.join(" "+n),f?u.className.baseVal=t:u.className=t)}function o(){return"function"!=typeof t.createElement?t.createElement(arguments[0]):f?t.createElementNS.call(t,"http://www.w3.org/2000/svg",arguments[0]):t.createElement.apply(t,arguments)}var l=[],r=[],c={_version:"3.2.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,t){var n=this;setTimeout(function(){t(n[e])},0)},addTest:function(e,t,n){r.push({name:e,fn:t,options:n})},addAsyncTest:function(e){r.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=c,Modernizr=new Modernizr;var u=t.documentElement,f="svg"===u.nodeName.toLowerCase(),p=o("input"),d="search tel url email datetime date month week time datetime-local number range color".split(" "),m={};Modernizr.inputtypes=function(e){for(var a,s,i,o=e.length,l=":)",r=0;o>r;r++)p.setAttribute("type",a=e[r]),i="text"!==p.type&&"style"in p,i&&(p.value=l,p.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(a)&&p.style.WebkitAppearance!==n?(u.appendChild(p),s=t.defaultView,i=s.getComputedStyle&&"textfield"!==s.getComputedStyle(p,null).WebkitAppearance&&0!==p.offsetHeight,u.removeChild(p)):/^(search|tel)$/.test(a)||(i=/^(url|email|number)$/.test(a)?p.checkValidity&&p.checkValidity()===!1:p.value!=l)),m[e[r]]=!!i;return m}(d),s(),i(l),delete c.addTest,delete c.addAsyncTest;for(var h=0;h<Modernizr._q.length;h++)Modernizr._q[h]();e.Modernizr=Modernizr}(window,document);
<input type="date">

<script>

  // Get new Date object and break down
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1; //January is 0!
  var yyyy = today.getFullYear();

  // Ensure there is a prefixed 0 on dates less than 10
  if(dd<10){
    dd='0'+dd
  }

  // Ensure there is a prexifed 0 on months less than 10
  if(mm<10){
    mm='0'+mm
  }

  // Modernizr checks if Input Type Date is supported
  if (Modernizr.inputtypes.date) {

    // Create formatted date output
    var today = yyyy+'-'+mm+'-'+dd;

    // Set value of all Inputs of type Date
    $('input[type=date]').val(today);

  } else {

    // Initiate jQuery DatePicker to all Input Type of Date
    $('input[type=date]').datepicker({
        format: "dd/mm/yyyy"
    });

    // Create formatted date output
    var today = dd+'/'+mm+'/'+yyyy;

    // Set value of all Inputs of type Date
    $('input[type=date]').val(today);

  }

</script>

Update (13/11/2015)

The code above has been edited, some browsers native date functionality requires the date value be formatted in the international format (yyyy-MM-dd), although it will take this value and format according to the browsers locales it must be set in the international format in the value field.

This presents an issue however when the browser does not offer an native functionality for date inputs, as the date will not be formatted according to the browsers locales, therefore it is displayed in the international format.

The script I have wrote offers a partial solution for this, as for my purposes the web application I am writing will only ever be used in the UK, therefore if the browser offers native date input functionality the value will be set to the international format, however if it does not support native date input, the value will be formatted in the UK format (dd-mm-yyyy). I am sure it would be quite simple to extend upon this solution to allow for formatting internationally according to different locales.

Craig Lowe
  • 83
  • 1
  • 9