Created
July 18, 2018 19:35
-
-
Save joanllenas/b466eede5b8105fad4f74f99c2be6ccb to your computer and use it in GitHub Desktop.
Controlled number input with Floats in Elm - the solution
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 (..) | |
import Html exposing (..) | |
import Html.Attributes as Attrs exposing (..) | |
import Html.Events exposing (..) | |
type Msg | |
= SetPrice String | |
type PriceField | |
= PriceField (Maybe Float) String | |
type alias Model = | |
{ price : PriceField } | |
model : Model | |
model = | |
{ price = PriceField Nothing "" } | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
SetPrice price -> | |
if String.right 1 price == "." then | |
( { model | price = PriceField Nothing price }, Cmd.none ) | |
else | |
let | |
maybePrice = | |
price |> String.toFloat |> Result.toMaybe | |
in | |
case maybePrice of | |
Nothing -> | |
( { model | price = PriceField Nothing price }, Cmd.none ) | |
Just p -> | |
( { model | price = PriceField (Just p) price }, Cmd.none ) | |
priceFieldToString : PriceField -> String | |
priceFieldToString priceField = | |
case priceField of | |
PriceField Nothing price -> | |
price | |
PriceField (Just price) _ -> | |
toString price | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ Html.form [] | |
[ label [] [ text "Price" ] | |
, input [ placeholder "Price", value (priceFieldToString model.price), onInput SetPrice ] [] | |
, br [] [] | |
, small [] [ text ("Price is: " ++ toString model.price) ] | |
] | |
] | |
main : Program Never Model Msg | |
main = | |
Html.program | |
{ init = ( model, Cmd.none ) | |
, update = update | |
, subscriptions = \_ -> Sub.none | |
, view = view | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment