skip to Main Content

My current code is:

<form id="search-form" hx-post="/search-api" hx-target="#search-result"></form>
<div class="search-wrapper">
    <div class="material-icons search-button md-8 md-light" role="button" type="submit" form="search-form">search</div>
    <div class="search-bar-wrapper">
         <textarea name="search" type="text" class="search-bar" id="search-bar" form="search-form" placeholder="search" oninput="autoResize(this)"></textarea>
    </div>
</div>
<div id="search-result"></div>

I can’t submit the form when I click the div, do I have to add some onclick="htmx.trigger(…)" like that? I can’t figure out how the htmx.trigger function works though.

2

Answers


  1. You can insert a hidden input field inside the div to help you access the containing form and submit.

    <div class="material-icons search-button md-8 md-light" role="button" form="search-form" onclick="this.querySelector('input').form.submit()">
        <input type="hidden">
        search
    </div>
    
    Login or Signup to reply.
  2. You can create an event listener on the "button" and in the callback function call submit() on the form element.

    const searchButton = document.getElementById('search-button');
    
    searchButton.addEventListener('click', e => {
      document.forms.searchForm.submit();
    });
    .search-button {
      cursor: pointer;
      padding: .3em;
      border: thin solid gray;
      border-radius: .3em;
      display: inline-block;
    }
    <form id="search-form" name="searchForm" hx-post="/search-api" hx-target="#search-result"></form>
    <div class="search-wrapper">
      <div id="search-button" class="material-icons search-button md-8 md-light">search</div>
      <div class="search-bar-wrapper">
        <textarea name="search" type="text" class="search-bar" id="search-bar" form="search-form" placeholder="search" oninput="autoResize(this)"></textarea>
      </div>
    </div>
    <div id="search-result"></div>

    But why not just a standard form with a button and a input element for a search string like below?

    <form name="searchForm" hx-post="/search-api" hx-target="#search-result">
      <button type="submit">search</button>
      <input name="search" class="search-bar" placeholder="search">
    </form>
    <div id="search-result"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search