Wes111222
Wes111222

Reputation: 163

Elm filter a list with input String

I have model

   type alias Model =
    { 
      url : String
    , devices : List Device
    , input : String
    , isFilter : Bool
    , deviceSuggestion : Maybe Device
    }

type alias Device =
    { 
      status : String
    , license_plate : String
    , device_id : String
    }

This is how i update the data but i have no idea how to do for filter after i type something in the search box

update msg model =
case msg of
    GotResult result ->
        case result of
            Ok devices ->
                ( { model | devices = devices }, portDevice devices )

            Err devices ->
                ( { model | error = Just "Error" }, Cmd.none )

    Tick _ ->
        ( model, fetchUrl )

    InputChange newInput ->
         ( { model | input = newInput //function filter here?}, Cmd.none)
        
    SearchFunction ->
        ({ model | input = "" }, toJS model.input)

This is my rendering View

renderPosts : Model -> Html Msg
    renderPosts model =
    div []
        [ h3 [] [ text "Filter List" ] ,
        , input [ type_ "text"
                , placeholder "Searching for devices"
                , onInput InputChange
                , value model.input
                , id "inputDevices"
                ] []
         --, checkListFunction model //check and filter list function here as well?
         , button [ onClick SearchFunction , id "searchDevice"] [ text "Search" ]
         ,
            div []
            ([ text "Device List" ] ++ List.map (\device -> renderPost device) model.devices) //display function
            ]

I want the output is like when i type the 1234 in searchbox then it detects and filter the below list with the license_plate in devices list.

**I tried the list.filter but it allows compare list to list. **I tried String.contains but i need 2 strings. It gives error because input box is String and license_plate is List

Any help is appreciate... https://www.w3schools.com/howto/howto_js_filter_lists.asp <<< Example of output

Upvotes: 1

Views: 1246

Answers (1)

glennsl
glennsl

Reputation: 29106

Below is an example of modifying your renderPosts function with a filteredDevices binding, showing how you could apply the filter:

renderPosts : Model -> Html Msg
renderPosts model =
    let
        filteredDevices =
            List.filter (\device => String.contains model.input device.license_plate) model.devices
    in
    div []
        [ h3 [] [ text "Filter List" ] ,
            ...
            div []
            ([ text "Device List" ] ++ List.map (\device -> renderPost device) filteredDevices)
            ]

Upvotes: 3

Related Questions