series0ne series0ne -4 years ago 173
Javascript Question

HTML5 button to trigger date input on mobile

I have a HTML5 design where I want to be able to use a button to display a date, but I want to use the HTML5 input type="date" to select the date.

Here is my code:

<button type="button" id="btnDate" class="btn btn-primary">
<span class="glyphicon glyphicon-calendar"></span> <span class="date">27 Jul 2015</span>
</button>
<input type="date" class="hidden" id="tbDate" />

<script type="text/javascript">
$(document).ready(function() {
$("#btnDate").click(function () {
$("#tbDate").focus();
});
});
</script>


I've tried focus() and click() - neither work...any ideas?

Answer Source

You need set val() for input. Hope this help

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button type="button" id="btnDate" class="btn btn-primary">
    <span class="glyphicon glyphicon-calendar"></span> <span class="date">27 Jul 2015</span>
</button>
<input type="date" class="hidden" id="tbDate" />

<script type="text/javascript">
    $(document).ready(function() {
        $("#btnDate").click(function () {
          var date = new Date("2015, 07, 27");
          var setDate = date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-"+("0" + date.getDate()).slice(-2);
            $("#tbDate").val(setDate);
        });
    });             
</script>

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