How to show datepicker on field focus only?

2019-09-20 13:13发布

问题:

I'm adding jquery mobile date picker but it shows the date picker by default. Instead, I want it to show up only on focus and to be hidden when the field loses focus...Any idea how ?

In the page header I added

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet"  href="/css/jquery.ui.datepicker.mobile.css" /> 
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
  //reset type=date inputs to text
  $( document ).bind( "mobileinit", function(){
    $.mobile.page.prototype.options.degradeInputs.date = true;
  });   
</script>   
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="/js/jQuery.ui.datepicker.js"></script>
<script src="/js/jquery.ui.datepicker.mobile.js"></script>

and a date field in the body to make it work:

<label for="date">Date Input:</label>
<input type="date" name="date" id="date" value=""  />   

回答1:

Unfortunately currently it can't be done unless you are willing to implement it yourself. jQuery Mobile datepicker was never intended to be officially released as a widget (maybe some day but it was never officially announced). Available code is nothing more then a wrapper around jQuery UI datepicker.

You can check it by yourself, here's an code snipet that shows a datepicker on pagecreate event:

$( ".ui-page" ).live( "pagecreate", function(){     
    $( "input[type='date'], input:jqmData(type='date')" ).each(function(){
        $(this).after( $( "<div />" ).datepicker({ altField: "#" + $(this).attr( "id" ), showOtherMonths: true }) );
    }); 
});

You can change it yourself but whats the point. In case you don't have time for custom implementation take a look at these 3rd party jQuery Mobile date pickers:

  1. First one is Mobi Pick: http://mobipick.sustainablepace.net/demo.html. Simple, easy and robust. Just the one you need. My favorite.

  2. Probably best one is : http://mobiscroll.com/. It used to be my favorite (still is if I need good UI). Mostly because it is robust with an excellent UI.

  3. Also an excellent one is Datebox: http://dev.jtsage.com/jQM-DateBox2/. Also robust but little buggy.

Also take a look at my other similar article: https://stackoverflow.com/a/13779992/1848600