How to initialize a datepicker on a field that is created us


Topic: How to initialize a datepicker on a field that is created using a javascript

amrinder_bajwa premium asked 6 days ago

Expected behavior Datepicker is working fine for a field that is already exist during the page load but it is not working for an input field that is dynamically added using the javascript.

Actual behavior The dynamically added field just working as a normal input field instead of a datepicker.

Resources (screenshots, code snippets etc.) This image shows two sections. The one in green contains fields which are already exist on the page and datepicker is working fine. The red section has been created dynamically using the javascript and datepicker fields are just acting like normal text fields.

function initiateDatePicker(n)
            {
                const options = {
                    format: "mm/dd/yyyy",
                };

                const myDatepicker = new twe.Datepicker(
                    document.getElementById(n),
                    options
                );
                myDatepicker.open();
            }

I also tried the above function to intialize the datepicker using the onClick event but console is throwing the following error:

Uncaught TypeError: twe.Datepicker is not a constructor at initiateDatePicker (create:1431:38) at HTMLDivElement.onclick (create:1:1)


Bartosz Cylwik staff answered 6 days ago

Hi! This is the best approach to do this. After adding an element to the DOM dynamicaly, you should call the initiateDatePicker method to initialize the element.

As of the error you are showing, you are using the umd version of the twe package? Did you import the package in a place that would allow for reading of the twe variable? You can try importing it like this if for example console.log(twe) doesnt show anything

import * as twe from "tw-elements"

amrinder_bajwa premium answered 5 days ago

Thank you so much for your help. I am using umd version of twe via the zip package provided to me. I was importing the package using the script tag with type="text/javascript"

<script type="text/javascript" src="{{ asset('/tw-elements/js/tw-elements.umd.min.js') }}"></script>

Changing it the type from text/javascript to module fixed the issue

<script type="module" src="{{ asset('/tw-elements/js/tw-elements.umd.min.js') }}"></script>

Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue
  • User: Free
  • Premium support: Yes
  • Technology: TW Elements
  • MDB Version: 2.0.0
  • Device: Browser
  • Browser: All
  • OS: All
  • Provided sample code: No
  • Provided link: No
Tags