bigskysoftware / htmx

</> htmx - high power tools for HTML
https://htmx.org
Other
38.2k stars 1.3k forks source link

How to target multiple ids with HTMX hx-target #1240

Open Zesshhi opened 1 year ago

Zesshhi commented 1 year ago

I have a dynamic form in my Django project which have 3 form fields

And i want to clear other form fields when im changing first form field but hx-target working only for one id and i dont rly know how, i was trying hx-swap-oob but nothing changed

i suppose to target all ids if i change first form field, using widget_tweaks package as well

template.html

<div class="mt-3">
    {{ form.contractor_counter.label_tag }}
    {% render_field form.contractor_counter class='form-select mt-2' autocomplete='off' hx-get='/objects/' hx-trigger='change' hx-target='#id_contractor_object' %}
</div>

<div class="mt-3">
    {{ form.contractor_object.label_tag }}
    {% render_field form.contractor_object class='form-select mt-2' autocomplete='off' hx-get='/sections/' hx-trigger='change' hx-target='#id_contractor_section' %}
</div>

<div class="mt-3">
    {{ form.contractor_section.label_tag }}
    {% render_field form.contractor_section class='form-select mt-2' autocomplete='off' hx-swap-oob='true' %}
</div>
andryyy commented 1 year ago

Can't you put all three forms in a new div with a specific ID and redrew all of them?

A dirty hack may be to use events and trigger n+1 on Update of n. 😄

It's probably easiest to loop that in Python or create a wrapper that includes all IDs.

Zesshhi commented 1 year ago

Can't you put all three forms in a new div with a specific ID and redrew all of them?

A dirty hack may be to use events and trigger n+1 on Update of n. smile

It's probably easiest to loop that in Python or create a wrapper that includes all IDs.

Can you help me?) How to write that

sabine commented 1 year ago

You can use the multi-swap extension: https://htmx.org/extensions/multi-swap/

Zesshhi commented 1 year ago

I was trying multi-swap but for some reason its just swaping first field

sabine commented 1 year ago

Untested:

hx-get="/objects/"
hx-trigger="change"
hx-ext="multi-swap"
hx-swap="multi:#id_contractor_object,#id_contractor_section"

Does the HTML response from /objects/ contain both #id_contractor_object and #id_contractor_section? :thinking: If not, you would need to make an endpoint that returns both if you really want to swap them at the same time with htmx. There might be simpler solutions in Django or even plain JavaScript (fetching from the two endpoints that you already seem to have).

flibustenet commented 1 year ago

You can use swap-oob in your response and specify each id you want to replace.