【问题标题】:Set multiple select boxes on a predefined array base (AlpineJS)在预定义的数组基础上设置多个选择框(AlpineJS)
【发布时间】:2022-01-17 20:04:43
【问题描述】:

我想创建一个带有选择框的多重过滤器列表,它已经用于创建选择计数。通过加载页面,可以预定义一些 selectedEvents(通过 GET 参数 + PHP 设置)。我已经在网上搜索了很多,但没有找到任何与 AlpineJS 类似的案例,如何将这些预定义的值设置为“已选择”。

在下面的示例中,我希望第一个选择了 ID 为 1000 的事件,第二个选择了 ID 为 1002 的事件。在这种情况下,第三个将没有选择。

有什么想法或建议吗? :)

<section class="panel" x-data='{
        events: [
                { id: "1000", name: "My 1st cool event" },
                { id: "1001", name: "My 2nd cool event" },
                { id: "1002", name: "Just a better event" },
        ],
        selectedEvents: [ 1000, 1002 ],
        countFilter: 3
    }
'>
<template x-for="_ in Array.from({ length: countFilter })">
                <select name="event_id[]" required>
                    <option value="">Please choose</option>
                    <template x-for="event in events" :key="event.id">
                        <option :value="event.id" x-text="event.name"></option>
                    </template>
                </select><br>
            </template>
<button type="button" @click="countFilter++">Add selection</button>
            <button type="button" @click="countFilter--" x-show="countFilter > 1">Remove selection</button>
</section>

【问题讨论】:

    标签: alpine.js alpinejs


    【解决方案1】:

    您可以通过绑定选项的selected 属性来动态选择默认选项,例如:selected="checkSelect(index, event.id)"。其中checkSelect 是检查实际select 元素是否具有提供的默认选项的函数。如果存在默认值并且当前选项的值等于默认选项,则返回true,因此当前选项将收到selected 属性。

    完整的例子:

    <section class="panel" x-data='{
            events: [
                    { id: "1000", name: "My 1st cool event" },
                    { id: "1001", name: "My 2nd cool event" },
                    { id: "1002", name: "Just a better event" },
            ],
            selectedEvents: [ 1000, 1002 ],
            countFilter: 3,
            checkSelect(select_index, option_id) {
                return option_id == this.selectedEvents[select_index]
            },
        }
    '>
    <template x-for="(_, index) in Array.from({ length: countFilter })">
        <select name="event_id[]" required class="block">
        <option value="">Please choose</option>
        <template x-for="event in events" :key="event.id">
            <option :value="event.id" x-text="event.name" :selected="checkSelect(index, event.id)"></option>
        </template>
        </select>
    </template>
    <button type="button" @click="countFilter++">Add selection</button>
    <button type="button" @click="countFilter--" x-show="countFilter > 1">Remove selection</button>
    </section>
    

    请注意,我们还在第一个循环中添加了一个index 变量,因此我们可以跟踪循环中的当前选择元素(我们将其用作checkSelect 函数的第一个参数)。

    【讨论】:

    • 谢谢你,就像一个魅力:)
    猜你喜欢
    • 2017-04-19
    • 2018-02-28
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多