vanjs-org / van

🍦 VanJS: World's smallest reactive UI framework. Incredibly Powerful, Insanely Small - Everyone can build a useful UI app in an hour.
https://vanjs.org
MIT License
3.77k stars 87 forks source link

select({ value: "..." }) does not select default item? #346

Closed danawoodman closed 1 month ago

danawoodman commented 1 month ago

When rendering a select with a value set, the select does not automatically select the item passed in as value:

function Form() {
  const data = reactive({
    current: "6",
    items: [
      { label: "Item 5", value: "5" },
      { label: "Item 6", value: "6" },
      { label: "Item 7", value: "7" },
    ],
  });

  return list(
    select({
      oninput: (e) => (data.current = e.target.value),
      value: () => data.current,
    }),
    data.items,
    (i) => t.option({ value: i.val.value }, i.val.label),
  )
}

To get the items to select, you have to pass selected: data.current === i.val.value in your option.

Is this expected behavior?

sirenkovladd commented 1 month ago

In fact, this is the expected behavior If you simplify your function to pure javascript, you will see that value is assigned to select, which does not yet have children here is an example in pure javascript https://jsfiddle.net/6csxohn4/

To fix this, you need to set the value after the children have been initialized for example, like this https://jsfiddle.net/1bpz2kah/

danawoodman commented 1 month ago

Ok cool, thanks for the examples :)

I'm assuming my option using selected is also perfectly valid?

Tao-VanJS commented 1 month ago

I'm assuming my option using selected is also perfectly valid?

Yes.