HTMX Trigger events to post data on clicking "Enter Key" or it's alternate methods
Asked Answered
Y

2

5

I need to trigger to fire an ajax call on clicking enter key. I tried using

<form class="align-items-center row" th:action="@{/addTask}"
            method="post" th:object="${formData}" hx-post="/todo/addTask"
            hx-include="#pageSize" hx-target="#result" hx-swap="innerHTML"
            hx-trigger="click[enterKey]">
            <div class="col-auto">
                <label>Item :</label>
            </div>
            <div class="col-auto">
                <input id="task" type="text" class="form-control"
                    placeholder="Tasks..." th:field="*{task}" />
            </div>
            <div class="col-auto">
                <input type="submit" class="btn btn-primary" />
            </div>
        </form>

But it didn't worked

I need a HTMX to trigger ajax call on clicking enter key

Yurikoyursa answered 19/6, 2023 at 18:31 Comment(1)
try keyup[enterKey]Coconut
R
9
keyup[keyCode==13]

worked for me, this page can help: https://www.toptal.com/developers/keycode/enter.

and this page describes how to chain events and properties, but indeed htmx validation errors could be improved ;)

https://htmx.org/attributes/hx-trigger/ --> main explanation here.

https://htmx.org/examples/keyboard-shortcuts/ ---> examples

also note that click is just a mouse click, wheras keyup or keydown are other events, events can be chained, or they can be triggered in sequence or alternative (see what , does in the above docs)

Rubino answered 11/7, 2023 at 7:59 Comment(0)
R
2
keyup[key=='Enter']

A more human readable option

Runthrough answered 26/6 at 6:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.