skip to Main Content

I’m looking for help with HTMX. I writing a simple FastAPI app with HTMX and Tailwind and MongoDB database.

I have such a form:

<form id="currencyForm" hx-get="/currency_history_check/EUR" hx-target="#result" hx-swap="innerHTML">
  <select name="currency_id" id="currency_id" onchange="updateFormAction()">
  </select>
  <button type="submit">Submit</button>
</form>
<div id="result">

</div>

And this script:

function updateFormAction() {
        var selectedCurrency = document.getElementById("currency_id").value;
        document.getElementById("currencyForm").setAttribute("hx-get", "/currency_history_check/" + selectedCurrency);
    }

Even though the link changes, the result still remains the same
enter image description here
enter image description here

When I choose a currency from the select, it does change inside the HTML, however it always shows me EUR values as a return nonetheless.

Where do I make the mistake?

2

Answers


  1. Chosen as BEST ANSWER

    I managed to fix this. Turns out I had set up wrong API endpoints.

    My previous one was:

    @app.get('/currency_history_check/{currency_id}', response_class=HTMLResponse)
    async def currency_history_check(currency_id: str):
        currency_id = currency_id.upper()
    

    And now I changed it to this:

    @app.get('/currency_history_check', response_class=HTMLResponse)
    async def currency_history_check(currency_id: str = Query(...)):
        currency_id = currency_id.upper()
    

    There was something to do with Query and Path parameters


  2. HTMX won’t catch up with the attribute change from the JavaScript, you have to call htmx.process('your selector'); to force HTMX to re-process the element:

    function updateFormAction() {
        htmx.find('#currencyForm').setAttribute('hx-get', '/blah');
        htmx.process('#currencyForm');
    }
    

    But in your case, you don’t need any of that. HTMX smart enough to add form fields to the request automatically (check Network tab of the Developer Tools in your browser).

    So your form could look like this:

    <form id="currencyForm" hx-get="/currency_history_check" hx-target="#result" hx-swap="innerHTML">
      <select name="currency_id" id="currency_id">
      </select>
      <button type="submit">Submit</button>
    </form>
    <div id="result">
    
    </div>
    

    And without any JavaScript HTMX will call /currency_history_check adding currency_id to the query string (e.g. /currency_history_check?currency_id=EUR).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search