Yousef Altaf
Yousef Altaf

Reputation: 2763

multiple bootstrap datepicker's on the same page with extending form

It's maybe old question to add more then date-picker's on the same page. But I have a different case here.

used library https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js

Here is the script for the datepicker

<script>
        $(document).ready(function () {
            $('.datepicker').datepicker({
                keyboardNavigation: false,
                forceParse: false,
                todayHighlight: true
            });
        });
    </script>

now multiple date-picker will work fine on the same page.

{!! Form::text('expiry_date', null, ['data-format'=>'D, dd MM yyyy', 'class'=>'form-control datepicker', 'placeholder'=>'yyyy-mm-dd']) !!}
{!! Form::text('expiry_date', null, ['data-format'=>'D, dd MM yyyy', 'class'=>'form-control datepicker', 'placeholder'=>'yyyy-mm-dd']) !!}

but the second datepicker here comes from extending form script

<script>
        let counter = 1;
        let limit = 10;

        function addInput(divName) {
            if (counter === limit) {
                alert("You have reached the limit of adding " + counter + " inputs");
            } else {
                let newdiv = document.createElement('div');
                newdiv.innerHTML = '<div class = "col-md-12"> <h4>Package ' + (counter + 1) + ' </h4> ...<div class="col-sm-6"><div class="form-group"><div id="date-popup2" class="input-group date">{!! Form::text("expiry_date", null, ["data-format"=>"D, dd MM yyyy", "class"=>"form-control datepicker", "placeholder"=>"yyyy-mm-dd"]) !!}<span class="input-group-addon"><i class="fa fa-calendar"></i></span></div></div></div>...';
                document.getElementById(divName).appendChild(newdiv);
                counter++;
            }
        }
    </script>

When the second datepicker populate it dose't work. Any idea.

Upvotes: 3

Views: 2020

Answers (2)

Liam
Liam

Reputation: 1920

It's because you're initiating the .datepicker(), before you have rendered the second datepicker object.

Maybe try something similar to this:

$(function() {
  $(this).datepicker();
  $('#date').append('<p>Other Date: <input onfocus="dateme(this);" type="text" class="datepicker"></p>')
});

function dateme(x){
  $(x).datepicker();
}

Just to explain what's going on here, I append a new datepicker input, which has an onfocus="" attribute, which calls a function containing the .datepicker function when the input is in focus.

Codepen Example: https://codepen.io/lthomas122/pen/XQyOMm

Upvotes: 3

mooga
mooga

Reputation: 3317

For fast isolation

$('.datepick').each(function(){
    $(this).datepicker({
            keyboardNavigation: false,
            forceParse: false,
            todayHighlight: true
        });
  // apply the rest
}); 

this here it will keep it isolated

Upvotes: 1

Related Questions