Khanzor
Khanzor

Reputation: 5010

Submit with enter key

Is there an idiomatic way for me trigger my formlet's submit action when a keydown event is pressed?

Should I drop back down to DOM manipulation, or is there some Enhancement that I can use?

Upvotes: 3

Views: 211

Answers (1)

Tarmil
Tarmil

Reputation: 11372

Unfortunately, at the moment there is no standard way to do this. We do intend to add it in a future version though, either as an Enhance combinator or as a new option to Enhance.WithCustomSubmit*.

We actually encountered the same problem when creating FPish, and we use the following workaround:

[<JavaScript>]
let TriggerOnEnter (formlet : Formlet<'T>) =
    formlet
    |> Formlet.MapElement (fun elem ->
        let e = JQuery.JQuery.Of(elem.Body)
        e.Keypress(fun _ k ->
            // Opera uses charCode
            if k?keyCode = 13 || k?charCode = 13 then
                JavaScript.SetTimeout (fun _ ->
                    e.Find("input[type=button]").Trigger("click").Ignore
                ) 100 |> ignore
            k.StopPropagation()
        ).Ignore
        elem
    )

Note that it triggers the first button in the form, so you might need adjustments to the jQuery selector to make it actually trigger the submit button.

Upvotes: 4

Related Questions