Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

n2fole00's avatar

AlpineJS - Select value from model passed as fn arg on change

Hi folks, I'm the process of developing this select tag that handles modules that will be added or removed from a course. However, when I select a module to add, the AlpineJS model value sent to addModule is "module.id" for some reason. I also tried $event.target.value.

How do I pass the value of the selected value (from the option) on change event to the addModule function?

Thanks.

<div x-data="courseModuleData">
    <label for="unusedModuleSelect">Available course modules</label>
    <select id="unusedModuleSelect" x-model="selectedModule" x-on:change="addModule(selectedModule)">
        <option default>Please select</option>
        <template x-for="module in allModules" :key="module.id">
            <option
                x-show="unusedModulesIncludes(module.id)"
                value="module.id"
                x-text="module.name"
            ></option>
        </template>
    </select>
    ...
</div>

<script>
document.addEventListener('alpine:init', () => {
    Alpine.data('courseModuleData', () => ({
        selectedModule: null,
        unusedModules: @json($unusedModules),
        courseModules: @json($courseModules),
        allModules: @json($allModules),
        modulesToAdd: [],
        modulesToDelete: [],
        addModule(moduleId) {
            const int_moduleId = parseInt(moduleId);
			debugger;
            // at this point moduleId = "module.id"
        },
        //...
    }));
});
</script>
0 likes
1 reply
gych's avatar
gych
Best Answer
Level 29

In your code you're using value="module.id" where module.id is set as string.

Use this instead

x-bind:value="module.id"

Or this if you prefer shorter syntax

:value="module.id"
1 like

Please or to participate in this conversation.