htmx

HTMX places whole HTML in div


I've got a form with an input. If the input gets a value, I'd like to fetch some descriptive information and show that underneath.

Removing all the decorative tags, the HTML boils down to:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      th:replace="web/template.xhtml :: template(~{::head},~{::body})">
    <body>
        <form method="post">
            <input id="articlenr" name="articlenr" class="input" type="text" placeholder="Article"
                data-hx-get="/articleStorageChange.xhtml" data-hx-target="#articleInfo"/>
            <div id="articleInfo" th:text="${bb.articleInfo}">...</div>

As can be seen, Thymeleaf is used to construct the page server side. And the data-hx-* notation is allowed (to prevent the IDE from complaining, but using hx-* instead does not solve the issue).

Upon entering something in the input, the HTMX fires the request, the page is correctly constructed, and then it should ONLY replace the articleInfo div. What it actually happens is that the whole page is put into the articleInfo div. So I see the form twice, and the descriptive information is present in that second form.

Typing in the input in either form correctly updates the description information in the second form.

Tested HTMX with 1.9.12 and 2.0.1.

Am I doing something wrong? Why does HTMX not only filter out the articleInfo div?


Using some old fashion jquery I was able to code it out myself. Basically a prove that it should work, but not an answer to why HTMX is not working as expected:

function articleInfo(){
    $.ajax({
        url: "/articleStorageChange.xhtml?articlenr=" + document.getElementById("articlenr").value,
        cache: false,
        success: function(html){
            $("#articleInfo").replaceWith($("#articleInfo", html));
        }
    });
}

Solution

  • The hx-target is only related to the element, where the content needs to be injected.

    To filter the content coming from the backend you either need to: