I’d like to trigger an action when a specific option is selected in select
tag. @click
works on every other tags, but when it doesn’t seem to work on option
. Is there a directive like @selected
where I can trigger an action when an option
is selected?
JavaScript
x
24
24
1
<html>
2
<head>
3
<script defer src="https://unpkg.com/alpinejs@3.3.4/dist/cdn.min.js"></script>
4
</head>
5
6
<body>
7
8
<div x-data="{}">
9
10
<!-- this does NOT work -->
11
<select>
12
<option @click="alert('option 1');">option 1</option>
13
<option @click="alert('option 2');">option 2</option>
14
<option @click="alert('option 3');">option 3</option>
15
</select>
16
17
<!-- this works -->
18
<button @click="alert('button clicked');">Click</button>
19
20
</div>
21
22
</body>
23
</html>
24
Advertisement
Answer
You can’t attach events to <option>
tags, but you can attach a change
event to the <select>
tag and use the value of the selected option.
JavaScript
1
6
1
<select x-on:change="alert($el.value)">
2
<option>option 1</option>
3
<option>option 2</option>
4
<option>option 3</option>
5
</select>
6