简体   繁体   中英

alpine.js select/option init value

I have the following select/option input

 <script defer src="https://unpkg.com/alpinejs@3.xx/dist/cdn.min.js"></script> <div x-data="{ selected_id: 1, options: [{label: 'Foo', id: 0}, {label: 'Bar', id: 1}] }"> <select x-model="selected_id"> <template x-for="option in options"> <option:value="option.id" x-text="option.label"></option> </template> </select> <div x-text="selected_id"></div> </div>

The initial selected value is Foo but the I specified select_id as 1 which corresponds to Bar .

How can I set the initial selected value based on the value of selected_id ?

Found the solution: https://github.com/alpinejs/alpine/issues/495

 <script defer src="https://unpkg.com/alpinejs@3.xx/dist/cdn.min.js"></script> <div x-data="{ selected_id: 1, options: [{label: 'Foo', id: 0}, {label: 'Bar', id: 1}] }"> <select x-model="selected_id"> <template x-for="option in options"> <option:value="option.id" x-text="option.label":selected="option.id == selected_id"></option> </template> </select> <div x-text="selected_id"></div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM