Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RoffDaniel's avatar

Handle button state

Hi all, I'm using Alpine.js for my buttons and when they are clicked I need to get their new state, because now I get it with getAttribute and when I click it I get its previous state. Is there any way to get its current state using document?

<button type="button" id="{{ $id }}"
        class="relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-indigo-600 focus:ring-offset-2 bg-gray-200"
        x-data="{ on: false }" role="switch" aria-checked="false"
        :aria-checked="on.toString()" @click="on = !on" x-state:on="Enabled"
        x-state:off="Not Enabled"
        :class="{ 'bg-indigo-600': on, 'bg-gray-200': !(on) }">
let block_2_button_1 = document.getElementById('block-2-switch-button-1').getAttribute('aria-checked');
let block_2_button_2 = document.getElementById('block-2-switch-button-2').getAttribute('aria-checked');
0 likes
1 reply
ramonrietdijk's avatar
Level 30

The code looks fine, but where exactly are you fetching the aria-checked attribute? If you are getting the value before Alpine.js has updated it, you'll get the previous value.

Please or to participate in this conversation.