5
votes

I have a hierarchy represented in a couple of dropdowns.

The parent dropdown selection drives the options of the children dropdown when an item is selected.

When a parent is selected, I am populating the children dropdown adding the first element to be blank ("") and display text to be "--select--".

I want this item to be the selected by default in the children's dropdown whenever the parent changes.

The problem is, the "selected" attribute does not seem to be doing its job.

childOptions : String -> Html msg
childOptions val =
    -- This selected attribute does not seem to work
    Html.option [ (Html.Attributes.selected (val == "")), Html.Attributes.value val ] [ Html.text val ]

You can see the behaviour here:

Ellie editor example

Select parent "entry 1" and then select child "1.2".

Now select parent "entry 2" and notice that it is ignoring the "selected" attribute, which is only true if the child entry is blank (""). The entry selected by default now is "2.2" which to me indicates it is keeping the position of the previously selected element "1.2".

Any ideas as to who this can be fixed?

1

1 Answers

0
votes

The problem appears to lie in the getOptions function; because the arguments to it do not change, its output (per <option> element) also will not change. And since the output does not change, Elm will not modify the selected property of the <option> elements.

(Since there's no Msg event for that <select>, Elm doesn't see the change events and the new value.)

getOptions : String -> Html msg
getOptions val =
    Html.option
        [ Html.Attributes.selected (val == "")
        , Html.Attributes.value val
        ]
        [ Html.text val ]

Each Hierarchy item should track it's selected value, and pass that to getOptions. Something like this:

getOptions : String -> String -> Html msg
getOptions selectedValue val =
    Html.option
        [ Html.Attributes.selected (val == selectedValue)
        , Html.Attributes.value val
        ]
        [ Html.text val ]