簡體   English   中英

根據 Alpine JS 中的選定選項切換輸入字段的可見性

[英]Toggle visibility of input fields based on the selected option in Alpine JS

我有一個選擇選項字段,我想根據所選選項切換某些輸入字段的可見性。 我知道@click事件在<option>上不起作用,所以有沒有辦法在<select>上使用@change或任何其他方式來實現這一點。

<div class="py-1" x-show="!open" x-transition>
    <span class="px-1 text-sm text-gray-600">Gender</span>
    <select @change="alert($el.value)" wire:model="gender">
        <option>Select Gender</option>
        <option value="male">Male</option>
        <option value="female">Female</option>
    </select>
</div>

Curretnly 我在這樣的單選按鈕上實現了這個

<div class="form-check">
    <input class="form-check-input appearance-none rounded-full h-4 w-4 border border-gray-300 bg-white checked:bg-[#60D619] checked:border-[#60D619] focus:outline-none transition duration-200 mt-1 align-top bg-no-repeat bg-center bg-contain float-left mr-2 cursor-pointer" type="radio" id="figurativeMarkWithWords" wire:model="tradeMarkType" @click="isFigurativeMark = true; isWordMark = true" value="figurativeMarkWithWords">
    <label class="form-check-label inline-block px-1 text-sm text-gray-600" for="figurativeMarkWithWords">
        Figurative Mark containing words
    </label>
</div>

現在我想把它變成一個選擇。

要根據元素中的所選選項切換某些輸入字段的可見性,您可以在元素上使用@change事件並使用所選選項的值來顯示或隱藏輸入字段。

以下是如何執行此操作的示例:

<div class="py-1" x-show="gender === 'male'" x-transition>
    <!-- input fields that should only be visible when the gender is male -->
</div>

<div class="py-1" x-show="gender === 'female'" x-transition>
    <!-- input fields that should only be visible when the gender is female -->
</div>

<div class="py-1" x-show="gender === 'other'" x-transition>
    <!-- input fields that should only be visible when the gender is other -->
</div>

<div class="py-1">
    <span class="px-1 text-sm text-gray-600">Gender</span>
    <select @change="gender = $event.target.value" wire:model="gender">
        <option>Select Gender</option>
        <option value="male">Male</option>
        <option value="female">Female</option>
        <option value="other">Other</option>
    </select>
</div>

在此示例中, x-show指令用於根據性別變量的值顯示或隱藏輸入字段。 元素上的@change事件使用所選選項的值更新性別變量,這反過來又更新了輸入字段的可見性。

資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM