You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AlpineJS实现:如何根据上一个下拉框选项动态改变当前下拉框值?

使用AlpineJS + CodeIgniter4 + Twig实现国家与货币下拉联动

我需要实现两个下拉选择框的联动效果:选择国家后,自动匹配对应的货币选项。技术栈采用CodeIgniter4搭配Twig模板引擎,使用AlpineJS完成前端交互,目前已实现需求,完整代码如下:

<div x-data="{ currency: '', currencies: {{ currencyArray|json_encode() }} }">

    <div class="form-group">
        <label for="country">{{'country'|translate}}</label>
        <select id="country" name="country" class="form-select" aria-label="country"
              @change="currency = $event.target.options[$event.target.selectedIndex].dataset.currencyId">

            {% for country in countryArray %}
               <option value="{{ country.id }}" data-currency-id="{{ country.currency_id }}">
                   {{ country.description|capitalize|translate  }}
               </option>
            {% endfor %}

         </select>
    </div>
              
    <div class="form-group">
        <label for="currrency">{{'currrency'|translate}}</label>
        <select class="form-select" aria-label="currrency">
            <template x-for="c in currencies">
                <option 
                :value='c.id'
                :selected="c.id === currency"
                x-text="c.name + ' - ' + c.description"
                >
                </option>
            </template>
        </select>
    </div>

</div>

核心实现逻辑

  • 用AlpineJS的x-data定义响应式变量:currency存储当前选中的货币ID,currencies接收后端通过Twig的json_encode传递的所有货币数据
  • 国家下拉框通过@change事件,获取选中选项的data-currency-id属性值,同步更新currency变量
  • 货币下拉框借助AlpineJS的x-for遍历货币列表,通过:selected判断当前货币ID是否与currency匹配,实现自动选中对应选项

内容的提问来源于stack exchange,提问作者Marko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 15:27:23