gpt4 book ai didi

javascript - 如何使用 x-init 使用 AlpineJS 设置下拉选项的 'selected' 属性

转载 作者:行者123 更新时间:2023-12-02 02:06:19 27 4
gpt4 key购买 nike

我有一个使用 AlpineJS 提交的表单。

使用 x-init 我想使用从 cookie 中读取的两个字母字符串将下拉列表默认设置为特定国家/地区。

如何使用在 initForm() 中获得的 2 字母代码来设置下拉列表的 selected 属性?

<div x-data="marketingForm()" x-init="initForm()">
<form id="formID-Contact" name="Contact" data-pageurl="http://localhost:8080/form-test/" class="">
<div>
<label for="country" >Country / Region</label>
<select id="country" name="country" autocomplete="country">
<option value='GB'>United Kingdom</option>
<option value='US'>United States</option>
<option value='CA'>Canada</option>
<option value='MX'>Mexico</option>
</select>
</div>
<a>
<button @click.prevent=submitMarketingForm() id='formSubmitButton'>submit</button>
</a>
</form>
</div>

和 JS

window.marketingForm = () => {
return {
detectedCountry: '',
initForm() {
let country = getCountry() // function that reads a cookie and returns 2 letter code eg. UK.
this.detectedCountry = country // how do I use this to set selected attribute of relevant option

},
submitMarketingForm(formID) {
// Do the form submitting stuff
}
}
}

所以假设 detectedCountry 设置为 UK 我想结束:

<select id="country" name="country" autocomplete="country">
<option selected value='GB'>United Kingdom</option>
<option value='US'>United States</option>
<option value='CA'>Canada</option>
<option value='MX'>Mexico</option>
</select>

最佳答案

如果国家的键等于检测到的国家,则只需绑定(bind)选定的属性。我建议将国家/地区存储在您的数据对象中。

<div x-data="marketingForm()" x-init="initForm()">
<form id="formID-Contact" name="Contact" data-pageurl="http://localhost:8080/form-test/" class="">
<div>
<label for="country" >Country / Region</label>
<select id="country" name="country" autocomplete="country">
<template x-for="country in countries">
<option
:value='country.key'
:selected="country.key === detectedCountry"
x-text="country.name"
>
</option>
</template>
</select>
</div>
<a>
<button @click.prevent=submitMarketingForm() id='formSubmitButton'>submit</button>
</a>
</form>
</div>


<script>
const marketingForm = () => {
return {
countries: [
{ key: 'GB', name: 'United Kingdom' },
{ key: 'US', name: 'United States' },
{ key: 'CA', name: 'Canada' },
{ key: 'MX', name: 'Mexico' },
],
detectedCountry: '',
initForm() {
let country = 'GB' // function that reads a cookie and returns 2 letter code eg. UK.
this.detectedCountry = country // how do I use this to set selected attribute of relevant option

},
submitMarketingForm(formID) {
// Do the form submitting stuff
}
}
}
</script>

关于javascript - 如何使用 x-init 使用 AlpineJS 设置下拉选项的 'selected' 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68409968/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com