Skip to content

How do I get a button id or value from x-on:click in Alpine JS?

Looking to extract a value or id in Alpine JS onclick, I thought this.id or this.value would work but no luck.

Returns

Alpine Expression Error: Can’t find variable: id

<button id="myBtn" value="100" x-on:click="alert(this.id);">Save</button>

Answer

This might help you.

<button @click="alert($event.target.getAttribute('message'))" message="Hello World">Say Hi</button>

$event.target will give you access to the clicked element.

Ref: https://alpinejs.dev/directives/on#the-event-object