Author - StudySection Post Views - 2,581 views
Bootstrap3

Bootstrap3 Datepicker is not working for Dynamically created elements

Let’s have a simple HTML code where Input is used and datepicker is used on an already existing element. Please include the required jquery and bootstrap3 files before loading the bootstrap datepicker library.
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap3 Datepicker</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
</head>
<body>
<div class="row">
<div class="col-xs-6">
<form method="post" style="margin:20px;">
<div class="form-group calendar-input">
<input type="text" class="form-control"/>
</div>
</form>
</div>
</div>
<script>
$('.calendar-input input').datepicker();
</script>
</body>
</html>

With the above HTML sample code, the datepicker looks like as shown in the below screenshot:
Datepicker

As you can see how simple it is to use the bootstrap3 datepicker on an already existing input.
But I faced an issue with dynamically created input elements, datepicker is not opened for such elements.

Let’s have a following screenshot:
Datepicker1

From screenshot 2, we can see that on click of link Add More Input, we can add more inputs on the page dynamically, but the issue here is that datepicker is not opened for such dynamically created inputs. So, what’s the solution?
I used following approach to resolve this issue:

Change the jquery datepicker function from
$('.calendar-input input').datepicker();
to
$('form').on('focus', '.calendar-input input', function(){
$(this).datepicker();
});

Now, I have used on event on already existing parent element and it is showing datepicker for dynamically added elements too as shown below:
Datepicker2

Microsoft Windows 10 is a widely used operating system in computers all over the world. If you have skills in Microsoft Windows 10 then you can get a Windows 10 Certification from StudySection which can help you in getting hired. A beginner level certification exam for newbies and an advanced level certification exam for experts is available on StudySection.

Leave a Reply

Your email address will not be published.