1

I have a button that I want to toggle the value on a html input element from 0 to 1 and vice versa but I can't figure out how to do it with Alpine JS.

// input will be 0 or 1
<input type="hidden" value="0" name="status" x-ref="status">

// Toggles the status between 1 and 0 
<button type="button" 
x-data="{ on: false }" :class="{ 'bg-gray-200': !on, 'bg-primary-600': on }" 
@click="$refs.status.value = 1"
>Toggle Status</button>

I was able to get the code above to change the input value to 1 but can't figure out how to get it to toggle it back and forth. Any ideas would mean a lot.

1 Answer 1

4

Here you go

<div x-data="{ status: false }">

    <form>
        <input type="hidden" value="0" name="status" x-model.number="status">


        <span x-text="status"></span>
        
        <button type="button" x-on:click="status = !status">
            Toggle Status
        </button>
    </form>
</div>

The global status is held at the div element. The status is outputted inside a span using x-text.

The hidden input is bound to the status using x-model and transforming the boolean value to a number using the .number modifier.

Update

For whatever reasons this does not work anymore, I created a new sample here: https://codepen.io/codedge/pen/wvgNqee

It just defines two x-data values, one for the boolean value and one for the integer one.

<div x-data="{ status: false, num: 0 }">

    <form>
        <input type="hidden" value="0" name="num">


        <span x-text="num"></span>
        
        <button type="button" x-on:click="status = !status; num = (status == true ? 1 : 0)">
            Toggle Status
        </button>
    </form>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work. Value is changed to "true" or "false" being strings. I need "0" and "1". Laravel validation treats "0" and "1" (even though they're strings) as boolean. But "true" and "false" as strings where "false" is seen as true because it's not an empty string. The .number modifier doesn't have effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.