Search code examples
javascripthtmldatepickermaterializetimepicker

How to programmatically open a time picker


I have a MaterializeCSS time picker element. I'd need to have it linked to a hidden input field, and (1) to trigger the opening of the clock dialog programmatically, from the click of a button. Also, (2) I'd need to intercept the time selection event.

Here is a sample code.

<html>
<head>
<!-- jQuery -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
<!-- Compiled and minified MaterializeCSS JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
</head>
<body>

<input type="hidden" id="mytimepickerelement" class="timepicker" class="validate">
<a class="waves-effect waves-light btn timepicker" onclick="showtimepicker();">Set time</a>

<script type="text/javascript">
function showtimepicker() {
  // (1) TODO ON $('#mytimepickerelement')
}
function initializetimepicker() {
    $('.timepicker').pickatime({
        default: '0:00',
        fromnow: 0,
        twelvehour: false,
        donetext: 'OK',
        cleartext: 'Clear',
        canceltext: 'Cancel',
        autoclose: false,
        ampmclickable: false,
        aftershow: function(){},
        // (2) SOMETHING ELSE TODO TO INTERCEPT TIME SELECTION/MODAL CLOSURE EVENT
    });
}
$(document.ready(intializetimepicker));
</script>
</body>
</html>

How can I solve (1) and (2) and have the button working?


Solution

  • About first I found it kind of strange. I simulated click on timepicker but nothing happens. So I delayed it in ~1ms and it works... I know it is weird solution but still it is solution.

    Sample HTML:

    <a onclick="ope();">adas</a>
    
    <div class="row">
    <div class="input-field col s12">
                            <label for="timepicker_ampm_dark">Time am/pm ( dark theme )</label>
                            <input id="timepicker_ampm_dark" class="timepicker" type="time"/>
                        </div>
                    </div>
    

    Js/jq:

    //Time Picker:
    $('.timepicker').pickatime({
        default: 'now',
        twelvehour: false, // change to 12 hour AM/PM clock from 24 hour
        donetext: 'OK',
      autoclose: false,
      vibrate: true // vibrate the device when dragging clock hand
    });
    
    function ope(){
      setTimeout(function(){
        $('label').click();
      },1);
    }