Input tag value updated by Flowbite datepicker doesn't trigger phx-change="validate"

166 Views Asked by At

When I select a date from the datepicker, the selected date shows in the date input box as text, but the "validate" event is not fired. The following is my related code based on Flowbite documentation (https://flowbite.com/docs/getting-started/phoenix/) . Do I need to do anything else to trigger the event?

core_component.ex

      <input
        phx-hook="Datepicker"
        type="text"
        id={@id || @name}
        name={@name}
        value={@value}
        class={[
          "bg-gray-50 border pl-8 border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full ps-10 p-2.5  dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500",
          @class
        ]}
        {@rest}
        placeholder="Select date"
      />

app.js

Hooks.Datepicker = {
  mounted() {
      const datepickerEl = this.el;
      new Datepicker(datepickerEl, {
        autohide: true,
        buttons: true,
        format: 'yyyy-mm-dd',
      });
  },
  updated() {
      this.mounted();
  }
}
1

There are 1 best solutions below

0
On BEST ANSWER

Turns out an event listener needs to be added to the datepicker hook as follows:

Hooks.Datepicker = {
  mounted() {
      const datepickerEl = this.el;
      new Datepicker(datepickerEl, {
        autohide: true,
        format: 'yyyy-mm-dd',
      });

      this.el.addEventListener("changeDate", e => {

        /// https://elixirforum.com/t/triggering-liveview-form-change-event-from-javascript/37073/9
        let event = new Event("change", {bubbles: true});
        this.el.dispatchEvent(event);
      })
  }

}