3

In Opa, how can I prevent a page reload when a form is submitted? When submit is pressed, I want to perform some client-side validation and only submit the form if validation passes.

I'm working with this form:

<form onready={_ -> ready()} id=#form_id>
  <input type="submit" value="Submit" />
</form>

This function successfully logs its message on submit, but still reloads the page:

ready() : void =
  do ignore(Dom.bind(#form_id, {submit}, ( _ -> Log.notice("submit","submitted"))))

This function fails to log its message and reloads the page:

ready() : void =
  do ignore(Dom.bind_with_options(#form_id, {submit}, ( _ -> Log.notice("submit","submitted")), [{prevent_default}]))

I'm avoiding using WFormBuilder because I need fine grained control over the html of the form and the validation error messages (which did not seem like an option in WFormBuilder when I experimented with it).

Thanks for your help.

nrw
  • 819
  • 2
  • 7
  • 22

1 Answers1

3

In the source of WFormBuilder, I found this attribute in its form html: options:onsubmit="prevent_default"

So snippet has the behavior I was looking for:

<form onready={_ -> ready()} id=#form_id options:onsubmit="prevent_default">
  <input type="submit" value="Submit" />
</form>

ready() : void =
  do ignore(Dom.bind(#form_id, {submit}, ( _ -> Log.notice("submit","submitted"))))
nrw
  • 819
  • 2
  • 7
  • 22
  • I'm still unsure why this is the way Opa handles this. Does anyone have some insight into what the `options` attribute and the `prevent_default` value are intended for? It seems to have very [limited documentation](http://doc.opalang.org/index.html#_syntax_extensions). – nrw Oct 10 '11 at 02:44
  • `options:onsubmit` is a list of options for the event handler of the onsubmit event. `prevent_default` has the same effect as [returning false](http://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false) or doing `e.preventDefault()` in the JS event handler. There are technical reasons why this decision cannot be made in the event handler itself in Opa (long story short: the event handler may be a asynchronous RPC-call). In short: I think you answered your question perfectly :) – akoprowski Oct 11 '11 at 11:01