Set value of Range input

Hi,

How do you programatically set the value of a Range input?

viewof my_slider = Range([0, 10], {value: 5, step: .1})

I guess the canonical way is:

    viewof my_slider.value = 1.2345;
    viewof my_slider.dispatchEvent(new CustomEvent("input"));

However this will not update the value, it will instead set it to an error state. Usually the value you calculate will fall between two steps. It will only update my_slider after you click on the slider.

Can you automatically select the nearest step?

1 Like

Itā€™s true that the current behavior is not the same as for the native inputs. But the two native inputs (type="number" and type="range") donā€™t have the same behavior either in that case.

type="range"

If we define the slider with:

viewof my_range = html`<input type="range" step="0.1" min="0" max="10" value="5" />`

and if we set the value with:

viewof my_range.value = 1.2345;
viewof my_range.dispatchEvent(new CustomEvent("input"));

the value is modified to 1.2 and no error is shown.

type="number"

If we define the number input with:

viewof my_number = html`<input type="number" step="0.1" min="0" max="10" value="5" />`

and if we set the value with:

viewof my_number.value = 1.2345;
viewof my_number.dispatchEvent(new CustomEvent("input"));

the value is modified and set to 1.2345, and an error is shown

It might be worth creating an issue in Issues Ā· observablehq/inputs Ā· GitHub

Ok, thanks, Iā€™ll have another look.

I noticed this behaviour doesnā€™t happen if the initial value is between steps.

Good catch!! I hadnā€™t noticed this, but it looks like others have brought it to Mikeā€™s attention in issue #120 and in Yuriā€™s comment on Synchronized Inputs. Looks like this broke in v0.7.13, which added validation. Hereā€™s a reproduction showing it working in 0.7.12 and breaking in 0.7.13. Iā€™ve bumped the issue.

2 Likes

For me (Windows, Firefox 86) both versions on this reproduction donā€™t work.
image

1 Like