Search code examples
javascripthtmlcssdatepickermaterialize

Displaying Datepicker when i click the button


I would like to display the datepicker when i click on the button. I have tried but i couldn't make it work. I am using Materialize Css. I have tried to use input type text but i don't want it.

<div class="container">
     <div class="row center">
       <i>Date</i>
       <button class="btn waves-effect waves-light datepicker" type="submit" name="action">PICK DATE</button>
     </div>
   </div>

jQuery:

$('.datepicker').pickadate({
    selectMonths: true, 
    selectYears: 15 
  });

Solution

  • In order to show the datepicker from a button, you need to invoke the show option.

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>jDatapicker JQuery</title>
      <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
      <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
      <script>
      $(function() {
        $( "#datepicker" ).datepicker();
      });
        function show_dp(){
          $( "#datepicker" ).datepicker('show'); //Show on click of button
         }
      </script>
    </head>
    <body>
     
    <p>Date: <input type="text" id="datepicker"></p>
      <button onclick="show_dp();">Show Datepicker</button> 
     
     
    </body>
    </html>

    Another option to make it so you don't need an input field:

    <!doctype html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8">
      <title>jDatapicker JQuery</title>
      <script src="//code.jquery.com/jquery-1.10.2.js"></script>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
      <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
      <script>
    
        function toggle_dp() {
          dp = $("#datepicker");
          if (dp.attr('datepicker')) {
            dp.datepicker('destroy');
            dp.removeAttr('datepicker');
          } else {
            dp.datepicker();
            dp.attr('datepicker', 1);
          }
    
    
        }
      </script>
    </head>
    
    <body>
    
      <div id="datepicker"></div>
      <button id="button" onclick="toggle_dp();">Toggle Datepicker</button>
    
    
    </body>
    
    </html>