Set value of Range input


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.


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.


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.


For me (Windows, Firefox 86) both versions on this reproduction don’t work.

1 Like