skip to Main Content

I have a custom datepicker like this

<input id='mydatepicker' data-mddatetimepicker='true' data-placement='left' data-trigger='focus' data-enabletimepicker='false' />

When I use it in html code work well. For example :

<div class="col-md-4" id="mydiv">
    <input id='mydatepicker' data-mddatetimepicker='true' data-placement='left' data-trigger='focus' data-enabletimepicker='false' />
</div>

But I want add this datepicker using replaceWith in document.ready.

<div class="col-md-4" id="mydiv">
    <div id="div2"></div>
</div>

<script>
    $(document).ready(function () {
        $("#div2").replaceWith("<input id='mydatepicker' data-mddatetimepicker='true' data-placement='left' data-trigger='focus' data-enabletimepicker='false' />");
    });
</script>

But when page loaded just display an simple input without datepicker. How can I do this replacement correctly?

I use this library for datepicker

2

Answers


  1. Try initialize the datepicker after replacing the content. Something like

     $(document).ready(function () {
            $("#div2").replaceWith(parameters);  
            $("#mydatepicker").datetimepicker(parameters);
        });
    
    Login or Signup to reply.
  2. Once you replace #div2 with your input html, you need to initialize your datepicker with follwoing code as suggested in documentation [1].

    const dtp1Instance = new mds.MdsPersianDateTimePicker(document.getElementById('dtp1'), {
      targetTextSelector: '[data-name="dtp1-text"]',
      targetDateSelector: '[data-name="dtp1-date"]',
    });
    

    See the following example.

    $(document).ready(function() {
      $("#div2").replaceWith("<input id='mydatepicker' data-mddatetimepicker='true' data-placement='left' data-trigger='focus' data-enabletimepicker='false' data-name='dtp1-text' />");
      
      const dtp1Instance = new mds.MdsPersianDateTimePicker(document.getElementById('mydatepicker'), {
      targetTextSelector: '[data-name="dtp1-text"]',
      targetDateSelector: '[data-name="dtp1-date"]',
    });
    });
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
    
    <link href="https://mds92.github.io/MD.BootstrapPersianDateTimePicker/src/mds.bs.datetimepicker.style.css" rel="stylesheet"/>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://mds92.github.io/MD.BootstrapPersianDateTimePicker/src/mds.bs.datetimepicker.js"></script>
    
    
    
    <div class="col-md-4" id="mydiv">
      <div id="div2"></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search