Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

javascript - Alpine JS Toggle Input Values

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.

question from:https://stackoverflow.com/questions/65912254/alpine-js-toggle-input-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...