logoalt Hacker News

t-writescode05/04/20251 replyview on HN

I like that it still feels like html. I think that's it's biggest selling point.

You write:

  <div id="moo" />
  <form hx-put="/foo" hx-swap="outerHTML" hx-target="#moo">
     <input hidden name="a" value="bar" />
     <button name="b" value="thing">Send</button>
  </form>
Compared to (ChatGPT helped me write this one, so maybe it could be shorter, but not that much shorter, I don't think?):

  <div id="moo" />
  <form>
     <input hidden name="a" value="bar" />
     <button name="b" value="thing" onclick="handleSubmit(event)" >Send</button>
  </form>

  <script>
  async function handleSubmit(event) {
    event.preventDefault();
  
    // the form submit stuff
    const form = event.target.form;
    const formData = new FormData(form);

    const submitter = event.target;
    if (submitter && submitter.name) {
      formData.append(submitter.name, submitter.value);
    }

    // hx-put
    const response = await fetch('/foo', {
      method: 'PUT',
      body: formData,
    });

    / hx-swap
    if (response.ok) {
      const html = await response.text();
      // hx-target
      const target = document.getElementById('moo');
      const temp = document.createElement('div');
      temp.innerHTML = html;
      target.replaceWith(temp.firstElementChild);
    }
  }
  </script>
And the former just seems, to me at least, way way *way* easier to read, especially if you're inserting those all over your code.

Replies

hirvi7405/05/2025

Yeah, the JS could technically be shorter, but your example is functional enough to get the point across.

Going with your example, how would you do proper validation with HTMX? For example, the input element's value cannot be null or empty. If the validation fails, then a message or something is displayed. If the validation is successful, then that HTML is replace with whatever?

I have successfully gotten this to work in HTMX before. However, I had to rely on the JS API for that is outside the realm of plain HTML attribute-based HTMX. At that point, especially when you have many inputs like this, the amount of work one has to do with the HTMX JS API starts to look at lot like the script tag in your example, but I would argue it's actually much more annoying to deal with.

show 2 replies