Using LiveView.JS to manipulate input values

I think the LiveView way to do this is indeed via JS.dispatch. The live_beats app is a good reference for these kind of things. For example they have a js_exec method via which you can call arbitrary functions on the target element.

However in your case, since you need to assign a property, it would look something like this though:

window.addEventListener("js:set", e => e.target[e.detail.key] = e.detail.value);

Then use JS.dispatch like this:

JS.dispatch('js:set', to: "#my-input", detail: %{key: "value", value: "hello"})

Or even simpler:

window.addEventListener("js:set_input_value", e => e.target.value = e.detail);
JS.dispatch('js:set_input_value', to: "#my-input", detail: "hello")
7 Likes