Search code examples
javascriptjqueryhtmlmaterialize

How to add and remove time or date picker materialize?


I'm facing a problem, where I want to create multiple time fields but clicking add button just like adding dynamic input fields. But when I trigger time on the dynamically created input fields it does not work. Please help I have attached the code snippet below for reference.

            <div class="row slot-container">
                <div class="input-field col s12">
                    <input type="text" placeholder="select date for demo" class="datepicker">
                </div>
                <div class="input-field col s6">
                    <input type="text" placeholder="from" class="timepicker">
                </div>
                <div class="input-field col s6">
                    <input type="text" placeholder="to" class="timepicker">
                </div>
            </div>
            <a class="waves-effect waves-light btn addSlots">Add Slots</a>
$(function(){
     $('.timepicker').pickatime({
       default: 'now', // Set default time: 'now', '1:30AM', '16:30'
       fromnow: 0, 
       twelvehour: true, // Use AM/PM or 24-hour format
       donetext: 'OK', // text for done-button
       cleartext: 'Clear', // text for clear-button
       canceltext: 'Cancel', // Text for cancel-button,
       container: 'body', // ex. 'body' will append picker to body
       autoclose: false, // automatic close timepicker
       ampmclickable: true, // make AM PM clickable
       aftershow: function(){} //Function for after opening timepicker
    });

    $(document).on('click','.addSlots',function(){
      $('.slot-container').after("<div class='row slot-container'><div class='input-field col s6'> <input type='text' placeholder='from' class='timepicker'> </div> <div class='input-field col s6'> <input type='text' placeholder='to' class='timepicker'> </div> </div>");
      });
    });

Solution

  • just changing the first line. before:

    $(function(){
    

    after:

    $(document).on('focus','.timepicker',function(){