Home > Mobile >  HTMX does not trigger get on load if it's a radio check
HTMX does not trigger get on load if it's a radio check

Time:05-05

I am working on Django and using htmx I have checkbox input, select tag and radio input both work as expected on page load it sends a request to an endpoint to the server to retrieve certain information which is rendered through a partial template. The problem is only radio deosn't trigger it when the appropriate input value is checked.

Here is the radio input.

<input id="option_{{ option.id }}"  type="radio"
                    name="radio_{{ question.id }}" value="{{ option.id }}" {% if question.required %} required
                    {% endif %} {% if question.disable %} disabled {% endif %} {% if option.id == radio_response %}
                    checked {% endif %} hx-get="{% url 'survey:dynamic_loader' %}" hx-trigger="load, change"
                    hx-target="#radio-result-{{question.id}}"/>

Is this a normal behaviour for htmx? Or I am doing something wrong.

CodePudding user response:

You should not put the load trigger on radio inputs. If you have 10 radio inputs, then the load trigger creates 10 requests in total from which 9 will not have the value you expect, because HTMX just extracts the actual state of a radio input when the page loads. Instead of that, you should put HTMX attributes on a parent (grouping) element. For example:

<div hx-get="{% url 'survey:dynamic_loader' %}" 
     hx-trigger="load, change"
     hx-target="#radio-result-{{question.id}}">
     hx-include="this"
  {% for option in options %}
  <input id="option_{{ option.id }}" 
       type="radio"
      name="radio_{{ question.id }}" 
      value="{{ option.id }}" 
      {% if question.required %} required{% endif %} 
      {% if question.disable %} disabled {% endif %} 
      {% if option.id == radio_response %}checked {% endif %} />
  {% endfor %}
</div>

This creates only one request on page load (and of course when the user clicks on a radio input) and it will have the correct value of the radio input. The hx-include="this" attribute includes all child inputs' value in the request.

  • Related