JasterV
September 4, 2024, 5:11pm
1
I have the following html code in a functional component
<form id="locale-dropdown" name="locale">
<.input type="select"
options={[
{dgettext("default", "Spanish"), "es"},
{dgettext("default", "English"), "en"}
]}
>
</.input>
</form>
Every time the user changes the language they want their page in, I want to trigger an http request to a controller. I am not using live view, how can I do this?
If you are not using LV, then you’ll have to resort to javascript.
It’s usualy done by hooking a change-event on the input and then submitting the form.
<form method="post" action="/" id="the_form">
<select onchange="go()" />
<option value="nl">NL</option>
<option value="en">EN</option>
</select>
</form>
<script type="text/javascript">
function go() {
document.getElementById('the_form').submit();
}
</script>
JasterV
September 4, 2024, 5:32pm
3
damn thats so inconvenient, I wish phoenix had a simpler way to do this
possibly you could change it to onchange="this.form.submit()"
and remove the script
tag.
It does: LiveView.
Otherwise Phoenix is not a JavaScript framework. You can use something like HTMx, Alpine, etc if you don’t like JS.
Also, I wouldn’t use on
in attributes and instead event listeners. A more reusable version (though I would still tweak… or just use a library):
<head>
<script defer>
window.addEventListener("DOMContentLoaded", () => {
for (el of document.querySelectorAll('[data-trigger-submit]')) {
el.addEventListener('change', () => {
el.closest('form').submit()
})
}
})
</script>
</head>
<body>
<form method="post" action="/" id="the_form">
<select data-trigger-submit>
<option value="nl">NL</option>
<option value="en">EN</option>
</select>
</form>
3 Likes