All threads / How do I add a new input to a form using AJAX

Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Kaolla Su 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] }
Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.