Toggle visibility of input fields based on the selected option in Alpine JS
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.
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 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>
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.
@JarekTkaczyk Thank you very much. This is what I needed. I didn't know in x-show you can check conditions, I though you can only put variables which resolve as either true or false.