【问题标题】:Change field value when button is clicked with AlpineJS使用 AlpineJS 单击按钮时更改字段值
【发布时间】:2021-04-29 23:28:25
【问题描述】:

有没有办法在使用 AlpineJS 单击按钮时更改字段值?

这是我的代码:

<div class="flex flex-col items-center" x-data="{on:false}">
    <div class="flex items-center w-full">
        <button type="button" class="bg-gray-200 relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500" aria-pressed="false" :aria-pressed="on.toString()" @click="on = !on" x-state:on="Enabled" x-state:off="Not Enabled" :class="{ 'bg-blue-600': on, 'bg-gray-200': !(on) }">
            <span aria-hidden="true" class="translate-x-0 pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200" x-state:on="Enabled" x-state:off="Not Enabled" :class="{ 'translate-x-5': on, 'translate-x-0': !(on) }"></span>
        </button>
        <div class="text-sm ml-3">Enable Button</div>
    </div>
    <div class="flex w-full bg-gray-50 p-4 mt-4 rounded-lg" x-show="on" x-transition:enter-start="transition ease-in duration-3000">
        <div class="flex flex-col items-center w-full" x-data="{on:false}">
            <input type="text" name="filesRequired" id="filesRequired">
            ...
        </div>
    </div>
</div>

基本上,我正在尝试在启用按钮 ({on:true}) 时将值“1”添加到 &lt;input type="text" name="filesRequired" id="filesRequired"&gt; 字段,如果 {on:false} 则删除该值

【问题讨论】:

    标签: alpine.js


    【解决方案1】:

    以下方法可行吗?当on 为真时,它使用x-bind: 设置value="1",并在on 为假时删除value

    &lt;input type="text" name="filesRequired" id="filesRequired" x-bind:value="on ? 1 : undefined"&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 2010-11-22
      • 2019-01-18
      • 1970-01-01
      相关资源
      最近更新 更多