#htmx #html #frontend

Day 5: Parameters & Payloads

Welcome to Day 5. GET requests are good, but apps need data exchange.

Automatic Parameters

If an element triggers a request (like an input), its value is sent automatically.

<input name="search" type="text" hx-get="/search" />
<!-- Sends: GET /search?search=value -->

hx-vals

Add extra static or dynamic JSON values to any request.

<button 
    hx-post="/vote" 
    hx-vals='{"userId": "42", "direction": "up"}'
>
    Upvote
</button>

Note: Use single quotes for the attribute so you can use double quotes for JSON.

Forms & hx-include

Standard forms work as expected.

<form hx-post="/save">
    <input name="title" />
    <button>Save</button>
</form>

But what if the button is outside the form?

<form id="note-form">
    <input name="note" />
</form>

<button hx-post="/save-note" hx-include="#note-form">
    External Save
</button>

hx-include allows you to grab values from other parts of the DOM. css selectors rule here.

Challenge for Day 5

  1. Create a sorting interface.
  2. A select dropdown for “Order By” (Name, Date).
  3. A separate checkbox for “Descending”.
  4. When the Select changes, it should include the checkbox value in its request.

Solution:

<label>
    <input type="checkbox" id="desc" name="desc" value="true"> Descending
</label>

<select 
    name="sort" 
    hx-get="/list" 
    hx-include="#desc" 
    hx-target="#list"
>
    <option value="name">Name</option>
    <option value="date">Date</option>
</select>

<div id="list"></div>

Now you can send complex data packages. Tomorrow: UX & Loading States.