Last active
January 23, 2017 03:54
-
-
Save jweir/9e8412a4fa0132866977626e337cb164 to your computer and use it in GitHub Desktop.
Enable decimal input in elm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (..) | |
-- solution based on https://groups.google.com/d/msg/elm-discuss/g7X0jTw87Ck/iudNZekGBQAJ by Witold Szczerba | |
import Html exposing (beginnerProgram, div, button, text) | |
import Html.Events exposing (onInput) | |
import Html.Attributes as HA | |
import String | |
type alias Model = | |
{ a : FloatField | |
, b : FloatField | |
, c : FloatField | |
} | |
type alias FloatField = | |
{ value : Maybe Float, input : String } | |
main : Program Never Model Msg | |
main = | |
beginnerProgram | |
{ model = | |
{ a = FloatField (Just 0.0) "0" | |
, b = FloatField (Just 0.0) "0" | |
, c = FloatField (Just 0.0) "0" | |
} | |
, view = view | |
, update = update | |
} | |
view : Model -> Html.Html Msg | |
view model = | |
div [] | |
[ Html.text ("5 x ") | |
, Html.input | |
[ HA.type_ "number" | |
, HA.value model.a.input | |
, onInput (Change (\str -> { model | a = (ffParse model.a str) })) | |
] | |
[] | |
, Html.input | |
[ HA.type_ "number" | |
, HA.value model.b.input | |
, onInput (Change (\str -> { model | b = (ffParse model.b str) })) | |
] | |
[] | |
, Html.input | |
[ HA.type_ "range" | |
, HA.value model.c.input | |
, onInput (Change (\str -> { model | c = (ffParse model.c str) })) | |
] | |
[] | |
, Html.text (toString (ffValue model.a * ffValue model.b)) | |
] | |
type alias Updater = | |
String -> Model | |
type Msg | |
= Change Updater String | |
ffValue : FloatField -> Float | |
ffValue ff = | |
ff.value |> Maybe.withDefault 0 | |
ffParse : FloatField -> String -> FloatField | |
ffParse ff str = | |
case String.toFloat str of | |
Err _ -> | |
FloatField Nothing str | |
Ok new -> | |
FloatField (Just new) str | |
update : Msg -> Model -> Model | |
update msg model = | |
case msg of | |
Change up str -> | |
up str |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment