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?
A couple of ways:
Dispatch a submit event to the form using javascript when the button is clicked.
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.
I think you've put HTMX attributes inside the button or the input tag that is used to submit the form, instead of the form itself. Otherwise, there's no difference between form submission in the normal way or the HTMX way!
You can move hx- attributes from the input (or button) tag to your form tag. 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 attribute of the input tag.
You can also use the button tag instead of input for submission:
<button type="submit" form="search-form">look up</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With