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
相关产品推荐
相关产品推荐

