Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I add a new input to a form using AJAX

Romain asked in Rails

Hello!

I'm trying to replace a Flatpickr input in a form using AJAX.
I have to do this because Flatpickr does not currently support dynamic update of its attributes

I can't find a way to pass the form object to the partial in my show.js.erb file and I don't even know if it's possible to do that.

Replacing the entire form could be a solution, however if the user has started filling in some entries, then triggering the AJAX call would reset everything.
I could also store the filled entries values before I replace the whole form and then spread them into the new form instance, but that seems odd to me.

Any hints? :)

My show.js.erb:

    document.querySelector(".timepicker").remove();
    document.querySelector("#booking-form").append(document.createRange().createContextualFragment("<%= j render(partial: 'timepicker', locals: { form: form, interval: @interval }) %>"));

The partial that I would like to render:

    = form.text_field :time,
                    class: "form-control timepicker",
                                    data: { controller: "flatpickr",
                                                    flatpickr_no_calendar: true,
                                                    flatpickr_enable_time: true,
                                                    flatpickr_date_format: "H:i",,
                                                    flatpickr_min_time: interval[:start_time]
                                                    flatpickr_max_time: interval[:end_time] }
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 76,990+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.