Home > Mobile >  Toggle visibility of input fields based on the selected option in Alpine JS
Toggle visibility of input fields based on the selected option in Alpine JS

Time:12-18

I have a select option fields and I want to toggle the visibility of some input fields based on the selected option. I got to know that @click event doesn't work on <option> so is there a way to achieve this using @change on <select> or any other way.

<div  x-show="!open" x-transition>
    <span >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 I implemented this on a radio button like this

<div >
    <input  type="radio" id="figurativeMarkWithWords" wire:model="tradeMarkType" @click="isFigurativeMark = true; isWordMark = true" value="figurativeMarkWithWords">
    <label  for="figurativeMarkWithWords">
        Figurative Mark containing words
    </label>
</div>

Now I want to transform this into a selection.

CodePudding user response:

To toggle the visibility of some input fields based on the selected option in a element, you can use the @change event on the element and use the value of the selected option to show or hide the input fields.

Here's an example of how you can do this:

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

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

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

<div >
    <span >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>

In this example, the x-show directive is used to show or hide the input fields based on the value of the gender variable. The @change event on the element updates the gender variable with the value of the selected option, which in turn updates the visibility of the input fields.

Source

  • Related