stic-lab
stic-lab

Reputation: 553

How to Toggle text using Livewire or AlpineJs when according to checkbox status

What I would like to do is:

Below is the example that I excepted to have but this example uses Javascript. I would like to implement the same behavior using livewire or/and alpinejs.

function myFunction() {
  var checkBox = document.getElementById("toogleA");
  var text = document.getElementById("text");
  if (checkBox.checked == true) {
    document.getElementById("text").innerHTML = "YES";
  } else {
    document.getElementById("text").innerHTML = "NO";
  }
}
/* Toggle A */

input:checked~.dot {
  transform: translateX(100%);
  background-color: #7456e3;
}


/* Toggle B */

input:checked~.dot {
  transform: translateX(100%);
  background-color: #7456e3;
}
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet" />



<!--Start toggle button-->
<div class="flex items-center justify-center w-auto mb-5">
  <!-- label -->
  <label for="toogleA" class="flex items-center cursor-pointer">
                    <!-- toggle -->
                    <div class="relative">
                        <!-- input -->
                        <input wire:model="person" id="toogleA" onclick="myFunction()" type="checkbox" name="test" value="person" class="sr-only" />
                        <!-- line -->
                        <div class="w-10 h-4 bg-gray-400 rounded-full shadow-inner"></div>
                        <!-- dot -->
                        <div class="absolute w-6 h-6 transition bg-white rounded-full shadow dot -left-1 -top-1"></div>
                    </div>
                    
                <div id="text" class="ml-3 font-medium text-gray-700">NON </div>

            </div>

        </div>

Upvotes: 0

Views: 2072

Answers (1)

Peppermintology
Peppermintology

Reputation: 10210

You can achieve this with just Livewire.

Component

class YourComponent extends Component
{
    public bool $toggleA = false;

    public function render()
    {
        return view('livewire.your-component');
    }
}

Component view

<label for="toggleA">Toggle</label>
<input wire:click="$toggle('toggleA')" type="checkbox" id="toggleA" />

<p>{{ $toggleA ? 'Yes' : 'No' }}</p>

The $toggle function is a special helper in Livewire specifically for toggling the value of boolean properties.

Upvotes: 2

Related Questions