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

Time:12-06

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>

CodePudding user response:

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

CodePudding user response:

Pass the Event with $event. Then you can handle it like in vanilaJs.

function hello(e) {
  console.log(e.target.getAttribute('id'))
}
 <script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>    
<button id="myBtn" value="100" @click="hello($event);">Save</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related