7

How to submit a form using submit button or input type submit outside of the form? In HTML It can be done easily using form ID but I didn't find the way to submit the form outside of the form in HTMX?

Can anybody help in this regard?

Haradhan Sharma
  • 111
  • 2
  • 6

2 Answers2

9

A couple of ways:

  1. Dispatch a submit event to the form using javascript when the button is clicked.

  2. Add the hx-post attribute on the external button and also add hx-include="#your-form-id". This will include all the inputs within the form in the request.

Alejandro
  • 886
  • 5
  • 5
  • thank you for help., `hx-vals` also necessary in my case. – Haradhan Sharma Feb 26 '22 at 18:19
  • 1
    You would only need to us hx-vals if you wanted to include additional data not already in the form. hx-include should be able to send all form data. Maybe you need to add a wildcard `hx-include="#your-form-id *"` – Alejandro Feb 26 '22 at 23:50
1

I think you've put HTMX attributes inside the button or input tag which is used for submission, instead of the form, otherwise, there's no difference between form submission in the normal way or the HTMX way!

You can move hx- attributes from the submission input tag to the form tag which is used for submission. Take a look at this example:

<form id="search-form"
    hx-get="/search" hx-trigger="submit" hx-target="#results-box">
    <input type="text" name="user-email" placeholder="a part of users email">
    <input type="text" name="user-name" placeholder="a part of users name">
</form>
<input type="checkbox" id="au-cbox" name="only-active-users" form="search-form">
<label for="au-cbox">show only active users</label>

<input type="submit" value="look up" form="search-form">

<div id="results-box"></div>

In this example, there are two inputs outside the form: a checkbox and the form's submit button. When you click on the look up button, htmx will send a GET request to the /search address, containing three query params: (1) user-mail (2) user-name (3) only-active-users (if checked!)

So there are two ways to show a field is contained in a form: (1) put the field inside the form tag or (2) declare the form inside the input tag.

You can also use the button tag instead of input for submission:

<button type="submit" form="search-form">look up</button>
Hamidreza
  • 1,465
  • 12
  • 31