Conditionally disable `preventDefault` when submitting forms to Elm

Is there a way to conditionally switch preventDefault to form submissions? I tried using onWithOptions below, but it seems that only the first parameter is used, although I can see its change using Debug.log when there is a name in the model.

 , onWithOptions "submit" (if model.name == "" then (Debug.log "prevent" { preventDefault = True, stopPropagation = True }) else (Debug.log "allow" { preventDefault = False, stopPropagation = False }) ) (Json.succeed FormSubmit) 

Updated with answer results

As @Tosh pointed out, hiding the button fixes the problem:

 , button [ onPreventClickHtml FormSubmit , Html.Attributes.hidden (model.name == "" |> not) ] [ text " prevent" ] , button [ onClick FormSubmit , Html.Attributes.hidden (model.name == "") ] [ text "allow" ] 

Where onPreventClickHtml :

 onPreventClickHtml : Msg -> Attribute Msg onPreventClickHtml msg = onWithOptions "click" { preventDefault = True, stopPropagation = True } (Json.succeed msg) 

Conditionally, the button display does not work :

 , (if model.name == "" then button [ onPreventClickHtml FormSubmit ] [ text " prevent" ] else button [ type' "submit", onClick FormSubmit ] [ text "allow" ] ) 

I use elm-mdl, so I found the solution more complicated because, in my experience, creating a custom onclick requires types that don't appear in elm-mdl, so they need to be duplicated.

 , if model.name == "" then Material.Options.nop else Material.Options.css "visibility" "hidden" , onPreventClick FormSubmit , if model.name == "" then Material.Options.css "visibility" "hidden" else Material.Options.nop , Button.onClick FormSubmit onPreventClick : Msg -> Property Msg onPreventClick message = Material.Options.set (\options -> { options | onClick = Just (onPreventClickHtml message) }) -- Duplicated from elm-mdl type alias Property m = Material.Options.Property (Config m) m -- Duplicated from elm-mdl type alias Config m = { ripple : Bool , onClick : Maybe (Attribute m) , disabled : Bool , type' : Maybe String } 

Another approach that worked for my scenario was to change the type of the button:

 , if model.name == "" then Button.type' "reset" else Button.type' "submit" 
+5
source share
1 answer

One simple suggestion on a workaround until someone shows us how to solve it.

How to create two buttons (with different options, as you showed), and depending on the condition, only one of them is displayed? You can use Html.Attributes.hide for this.

+3
source

Source: https://habr.com/ru/post/1257944/


All Articles