Search code examples
javascripthtmlmaterialize

How to add materialize Date picker


I am new to front-end development, I am trying to add a date picker (Materialize framework). I spent a lot of time searching the internet for

"how to add materialize date picker".

But I couldn't find the solution to my problem.

<html>
  <head>
  <!--Import Google Icon Font-->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <!--Import materialize.css-->
  <link rel="stylesheet" 
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-
beta/css/materialize.min.css">

  <!--Let browser know website is optimized for mobile-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>

<body>

<input type="text" class="datepicker">
  <!--JavaScript at end of body for optimized loading-->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
  <script
 src="http://code.jquery.com/jquery-3.3.1.js"
 integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
 crossorigin="anonymous"></script>
 <script>
  document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.datepicker');
var instances = M.Datepicker.init(elems, options);
 });

 // Or with jQuery

  $(document).ready(function(){
   $('.datepicker').datepicker();
  });
 </script>
   </body>
 </html>

Solution

  • Using the documentation instructions:

      // Using with jQuery
      $(document).ready(function(){
        $('.datepicker').datepicker();
      });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    =<!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
    
    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
    <body>
    <input type="text" class="datepicker">
    </body>

    Note

    I just suggest you first import jquery in your HTML and then materiliaze.js as shown above